【发布时间】:2014-07-27 12:39:33
【问题描述】:
如果你创建新的 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
}
*/
【问题讨论】:
-
这是在 beta 2 中修复的 :)
-
没有 Swift 方面的专家,但上面的方法不适用于 XCode 6 GM。我不得不使用“覆盖 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { ” 来构建我的项目。
标签: ios xcode uitableview swift