Swift 中的 UITableView [英] UITableView in Swift

查看:18
本文介绍了Swift 中的 UITableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力弄清楚这段代码片段有什么问题.这目前在 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
    }

推荐答案

另见 matt 的回答,其中包含解决方案的后半部分

Also see matt's answer which contains the second half of the solution

让我们找到一个无需创建自定义子类或笔尖的解决方案

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? 而不是 as

and we have to cast using as? not 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆