Swift2 中的 UITableViewDataSource 错误

标签 uitableview swift2 xcode7

我正在学习 Swift,在编写一些代码行时,屏幕上出现错误,显示:类型 JVViewController (类名) 不符合协议(protocol)'UITableViewDataSource'。如果我在其他应用程序中执行了完全相同的操作并且我从未遇到过此类问题,我不知道为什么这会出现在我的文件中。

请让我知道如何解决这种情况。 谢谢!

最佳答案

如果一个类不符合协议(protocol),则意味着你需要实现一些协议(protocol)方法。如果在UITableViewDataSource上,则需要实现以下方法:

它定义了您将在 tableView 上显示的 tableViewCell 的数量

tableView(_:numberOfRowsInSection:)

它定义了每个tableViewCell的设置

tableView(_:cellForRowAtIndexPath:)

也许您忘记实现一个或这两个数据源方法。

例如:

class JVViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {

    ...

    var collectionItems = ["One", "Two", "Three"]    

    ...

    //Quantity of rows
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.collectionItems.count;
    }

    //Row settings
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

        cell.textLabel?.text = self.collectionItems[indexPath.row]

        return cell
    }

    ...

}

您可以在Apple文档中找到更多信息:https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDataSource_Protocol/

关于Swift2 中的 UITableViewDataSource 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32636631/

相关文章:

使用 Swift 2 进行 Base64 编码/解码

ios - 二元运算符 '&' 不能应用于类型 'SCNetworkReachabilityFlags' 和 'Int' 的操作数

ios - Xcode 7 beta 4 构建错误 - com.apple.CoreSimulator.SimRuntime.iOS-9-0

ios - swift 2 : Cannot invoke 'addAnnotation'

iphone - 不确定如何处理 “Terminating app due to uncaught exception ' NSInvalidArgumentException'”

ios - 使用非自数据源和委托(delegate)以编程方式创建 UITableView

ios - ViewController 不访问您的元素

swift2 - UIApplication.sharedApplication() 不可用

ios - UITableViewCell 展开和折叠

ios - 初始显示时 UITableViewCell 高度错误