我正在学习 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/