Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift tableView.dequeueReusableCell Never Returning Nil

This is my Swift code to generate my table view. I am trying to set up a tableView with detail labels. The problem is that the following code is never called.

if (cell == nil) {
            println("1")
            cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "CellSubtitle")
            //cell = tableViewCell
        }

Here is the code you need for the method:

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
    println("start TableViewCellForRowAtIndexPath")
    var cell: UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("CellSubtitle", forIndexPath: indexPath) as UITableViewCell
    if (cell == nil) {
        println("1")
        cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "CellSubtitle")
        //cell = tableViewCell
    }

    cell.textLabel.text = instructions[indexPath.row].text
    println("2")
    //cell.detailTextLabel
    cell.detailTextLabel.text = "HI"
    println("3")

Here is the console output for the method:

start load
1
2
done load
start TableViewCellForRowAtIndexPath
2
fatal error: Can't unwrap Optional.None
(lldb) 

How can I initialize the detailTextLabel in order to insert text? When I try to set the text for the label, I receive

fatal error: Can't unwrap Optional.None. 

Why am I receiving this error?

like image 781
Jacob Avatar asked Jun 12 '14 15:06

Jacob


1 Answers

You don't need to check if the cell is nil using this dequeue method, as long as you've register a cell class for reuse, or provided a prototype in Interface Builder.

let cell = tableView.dequeueReusableCellWithIdentifier("CellSubtitle", forIndexPath: indexPath) as! UITableViewCell

If however, you want to continue manually initializing the cells, you can use the following dequeue method instead. (keep in mind, this is the old way)

let cell = tableView.dequeueReusableCellWithIdentifier("CellSubtitle") as? UITableViewCell

Then as far as initializing the detailTextLabel goes, you don't have to. It's built into the cell, and by specifying that the cell's style should be subtitle, that label will be set up for you.

Note that the casts aren't necessary in Swift 2.

like image 111
Mick MacCallum Avatar answered Oct 19 '22 12:10

Mick MacCallum