我正在努力弄清楚这段代码有什么问题。这目前在 Objective-C 中有效,但在 Swift 中,这只会在方法的第一行崩溃。它在控制台日志中显示一条错误消息:Bad_Instruction
。
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
if (cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell")
}
cell.textLabel.text = "TEXT"
cell.detailTextLabel.text = "DETAIL TEXT"
return cell
}
最佳答案
另见 matt's answer其中包含解决方案的后半部分
让我们在不创建自定义子类或 nib 的情况下找到解决方案
真正的问题在于 Swift 区分可以为空的对象 (nil
) 和不能为空的对象。如果您没有为您的标识符注册一个 nib,那么 dequeueReusableCellWithIdentifier
可以返回 nil
。
这意味着我们必须将变量声明为可选:
var cell : UITableViewCell?
而且我们必须使用 as?
而不是 as
//variable type is inferred
var cell = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL")
}
// we know that cell is not empty now so we use ! to force unwrapping but you could also define cell as
// let cell = (tableView.dequeue... as? UITableViewCell) ?? UITableViewCell(style: ...)
cell!.textLabel.text = "Baking Soda"
cell!.detailTextLabel.text = "1/2 cup"
cell!.textLabel.text = "Hello World"
return cell
关于Swift 中的 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24022763/