加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在Swift中的UITableView

发布时间:2020-12-14 06:11:26 所属栏目:百科 来源:网络整理
导读:我正在努力弄清楚这段代码段出了什么问题。这将工作在Objective C,但在Swift这只是崩溃的方法的第一行。它不给出错误消息,只有Bad_Instruction。 func tableView(tableView: UITableView!,cellForRowAtIndexPath indexPath: NSIndexPath!) - UITableViewCe
我正在努力弄清楚这段代码段出了什么问题。这将工作在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?不是

//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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读