Swift中的简单UITableView - 意外地发现没有

sol*_*eil 15 uitableview ios swift

非常简单的代码:

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
}
Run Code Online (Sandbox Code Playgroud)

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

fatal error: unexpectedly found nil while unwrapping an Optional value
Run Code Online (Sandbox Code Playgroud)

BookTableViewCell的定义如下:

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
    }

}
Run Code Online (Sandbox Code Playgroud)

bookLabel正好连接在Storyboard的Prototype单元格中.为什么我收到此错误?

mli*_*liu 77

如果您正在使用故事板,请确保在文件开头没有此行:

self.tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "customCell")
Run Code Online (Sandbox Code Playgroud)

它将覆盖故事板,因此,故事板中的出口链接将被忽略.

  • 这对我来说是正确的答案......正在拉我的头发. (6认同)

upl*_*com 20

我收到此错误是因为我没有在自定义单元格的故事板中写入标识符.

故事板

还要确保它与您的代码匹配:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {

        let cell = tableView.dequeueReusableCellWithIdentifier("CustomTableCell") as CustomTableCell

        ...
    }
Run Code Online (Sandbox Code Playgroud)


Hie*_* Vo 9

可能是你在Main.Storyboard中的视图在ViewController文件中丢失了它的IBOutlet引用,只是再次链接它.


Nat*_*ook 7

在代码中创建视图时,其IBOutlet属性不会正确连接.您想要从以下版本获得的版本dequeueReusableCellWithIdentifier:

let cell = tableView.dequeueReusableCellWithIdentifier("BookCell") as BookTableViewCell
Run Code Online (Sandbox Code Playgroud)