Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift UITableViewCell detailTextLabel.text throws error 'fatal error: Can't unwrap Optional.None'

This is my Swift code to generate my table view. I am trying to set up a tableView with detail labels. I believe that the problem is created because

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

is never called, therefore the cell is never initialized with the UITableViewCellStyle.Subtitle style. Here is the needed code for the method:

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
    println("start TableViewCellForRowAtIndexPath")
    var cell: UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("CellSubtitle") 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?

The cell was not created in a story board. I initialized the cell or registered its class using tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "CellSubtitle")

like image 871
Jacob Avatar asked Jun 12 '14 17:06

Jacob


1 Answers

I assume that you made your cell in the storyboard, so that's why the "if" clause is never called. You just need to change the cell's style to be "Subtitle" in the inspector in the storyboard (and delete that if clause).

like image 143
rdelmar Avatar answered Sep 22 '22 17:09

rdelmar