Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple UITableView in Swift - unexpectedly found nil

Pretty simple code:

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
}

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

fatal error: unexpectedly found nil while unwrapping an Optional value

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
    }

}

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

like image 402
soleil Avatar asked Jul 18 '14 20:07

soleil


2 Answers

If you're using storyboard, make sure you don't have this line at the start of your file:

self.tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "customCell")

It will overwrite the storyboard and as a result, the outlet links in the storyboard are ignored.

like image 190
mliu Avatar answered Nov 10 '22 22:11

mliu


I was getting this error because I didn't have the identifier written in the Storyboard of the Custom Cell.

StoryBoard

Also make sure it matches you code in:

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

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

        ...
    }
like image 20
uplearned.com Avatar answered Nov 10 '22 22:11

uplearned.com