iOS 在 UIViewController 中手动增加 TableView 出现 Type 'SomeViewController' does not confirm to protocol 'UITableViewDataSource' 问题的解决办法

2015-1-28   /   字数:1030   /   阅读数:12818   /   分类: iOS & Swift     

许多时候我们都有在普通的继承自 UIViewController 的控制器中使用 TableView 的需求,这时候就需要当前控制器类继承 UITableViewDelegate 和 UITableViewDataSource,然后再初始化:

@IBOutlet weak var firstTableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    firstTableView.delegate = self
    firstTableView.dataSource = self
}

这时候,firstTableView.dataSource = self 这一行会报错:

Type 'SomeViewController' does not confirm to protocol 'UITableViewDataSource'

解决方案如下:

在该类中新增如下方法:

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("UserCenter", forIndexPath: indexPath) as UITableViewCell
        
        cell.textLabel.text = indexPath.row.description
        
        return cell
    }

最终运行结果如下:

Image

WRITTEN BY

avatar

评论:

jasoncool
2015-09-09 11:30
你这个DEMO应该把类名的继承实现关系描述清楚吧?
你的类应该是实现了UITableViewDelegate和UITableViewDataSource这两个protocol吧?
在Datasource中有两个非选择性方法必须实现。

发表评论:

© 2011-2024 岁寒  |  Powered by Emlog