Swift 中的简单 UITableView - 意外发现 nil [英] Simple UITableView in Swift - unexpectedly found nil

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

问题描述

非常简单的代码:

func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
    return 1
}

func tableView(tableView:UITableView!, numberOfRowsInSection section:Int) -> Int {
    return 5
}


func tableView(tableView:UITableView!, cellForRowAtIndexPath indexPath:NSIndexPath!) -> UITableViewCell! {
    let cell: BookTableViewCell = BookTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "BookCell")
    println("ip: (indexPath.row)")
    cell.bookLabel.text = "test"

    return cell
}

在 cell.bookLabel.text 行我得到这个:

On the cell.bookLabel.text line I get this:

fatal error: unexpectedly found nil while unwrapping an Optional value

BookTableViewCell 定义如下:

The BookTableViewCell is defined like this:

class BookTableViewCell: UITableViewCell {

    @IBOutlet var bookLabel: UILabel

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

并且 bookLabel 已正确连接到 Storyboard 的 Prototype 单元格中.为什么我收到这个错误?

And bookLabel is correctly hooked up in a Prototype cell in the Storyboard. Why am I getting this error?

推荐答案

当您在代码中创建视图时,它的 IBOutlet 属性没有正确连接.您想要从 dequeueReusableCellWithIdentifier 返回的版本:

When you create a view in code, its IBOutlet properties don't get hooked up properly. You want the version that you get back from dequeueReusableCellWithIdentifier:

let cell = tableView.dequeueReusableCellWithIdentifier("BookCell") as BookTableViewCell

这篇关于Swift 中的简单 UITableView - 意外发现 nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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