Swift中的UITableView [英] UITableView in Swift
问题描述
我正在努力弄清楚这段代码的错误。这目前在Objective-C中工作,但在Swift中,这只是在方法的第一行崩溃。它在控制台日志中显示错误消息: Bad_Instruction
。
I'm struggling to figure out what's wrong with this code snippet. This is currently working in Objective-C, but in Swift this just crashes on the first line of the method. It shows an error message in console log: 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
}
推荐答案
请参阅亚特的回答,其中包含解决方案的后半部分
Also see matt's answer which contains the second half of the solution
让我们在不创建自定义子类或nib的情况下找到解决方案
Let's find a solution without creating custom subclasses or nibs
真正的问题在于Swift可以区分可以为空的对象( nil
)和不能为空的对象。如果您没有为您的标识符注册一个nib,那么 dequeueReusableCellWithIdentifier
可以返回 nil
。
The real problem is in the fact that Swift distinguishes between objects that can be empty (nil
) and objects that can't be empty. If you don't register a nib for your identifier, then dequeueReusableCellWithIdentifier
can return nil
.
这意味着我们必须将变量声明为可选:
That means we have to declare the variable as optional:
var cell : UITableViewCell?
我们必须使用进行投射?
不 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!