Skip to main content
 首页 » 操作系统

ios之UITableView 和 UITableViewDataSource

2024年01月01日34kevingrace

因此,我在 Xcode 中收到“Type ViewController does not conform to protocol UITableViewDataSource”错误。我已经实现了所需的功能:

  • cellForRowAtIndexPath
  • 节中的行数

我什至确定我已经告诉 Xcode 有多少部分(这不是必需的)。这是一个单 View 应用程序,我已确保在 Storyboard 中正确设置了我的引用。所以我的奥特莱斯是我的 View 和我的 TableView 。我的引用 socket 设置为数据源和委托(delegate)是我的 TableView 。

这是代码。

ViewController.swift

import UIKit 
 
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 
    @IBOutlet weak var tableView: UITableView! 
 
    var items: [String] = ["We", "Dislike", "Swift", "Very", "Much", "Right", "Now"] 
 
    override func viewDidLoad() { 
        super.viewDidLoad() 
        // Do any additional setup after loading the view, typically from a nib. 
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") 
 
        tableView.delegate = self 
        tableView.dataSource = self 
    } 
 
    override func didReceiveMemoryWarning() { 
        super.didReceiveMemoryWarning() 
        // Dispose of any resources that can be recreated. 
    } 
 
    func numberOfSectionsInTableView(tableView: UITableView) -> Int{ 
        return 1 
    } 
 
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
        return self.items.count 
    } 
 
    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { 
 
        let cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath:indexPath) as UITableViewCell 
        cell.textLabel?.text = self.items[indexPath.row] 
 
        return cell 
    } 
 
    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { 
        println("You selected cell #\(indexPath.row)!") 
    } 
 
} 

编辑:另外,我知道我不应该需要 tableView.delegate 和 tableView.dataSource,因为我已经在 Storyboard 中分配了它们,但我想我会包括它们以确保你们都知道我知道有他们设置。

请您参考如下方法:

UITableViewDataSource 协议(protocol)发生了一点变化。尝试:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell