如果您创建新的 UITableViewController 类,您将看到重写的注释方法:
/*
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
您可以取消注释方法,它不会因为错误而工作
'UITableView?' does not have a member named 'dequeueReusableCellWithIdentifier'
原因是:tableView被定义为可选类型”UITableView?“并且您必须在调用该方法之前解开 tableView。例如如下所示:
let cell = tableView!.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
但我们可以让它们隐式解包选项并使用 tableView 而不使用!
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
return cell
}
问题是:为什么 xcode 将它们定义为可选?与隐式解包的选项相比,它有什么理由或优点吗?我们能确定这个方法总是得到非空值吗?
我们还会遇到另一个错误
Constant 'cell' inferred to have type 'AnyObject!', which may be unexpected
Type 'AnyObject!' cannot be implicitly downcast to 'UITableViewCell'; did you mean to use 'as' to force downcast?
我们可以通过将 UITableViewCell 添加到末尾来修复它,如下所示:
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
我不知道为什么模板默认情况下看起来不像这样:
/*
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell //or your custom class
// Configure the cell...
return cell
}
*/