user3210784
user3210784

Reputation: 499

Access to Custom UITableViewCell UILabel Text in Swift throws error

I'm trying to create a custom UITableViewCell, including my own UILabel inside.

I've created a single view application with Swift, and added a Cocoa Touch Class with .xib file, than I add the UILabel and create an Outlet in the new file(CustomCell Class).

In the main StoryBoard I've added a UITableView, and initialize it with data (implement UITableViewDataSource and UITableViewDelegate).

When I'm trying to access to the text property in the UILabel, it fail with that error:

fatal error: Can't unwrap Optional.None

This is my CustomCell Class:

import UIKit

class CustomCell: UITableViewCell {

    @IBOutlet var myLbl: UILabel

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    func SetValue(value: String){
        myLbl.text = value  // Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
    }
    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
}

Update: Here is the code the creates the cells in the main ViewController:

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{
        var cell = CustomCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Default")
        cell.SetValue(stringArray[indexPath.row])
        return cell;
    }

Upvotes: 1

Views: 2226

Answers (1)

drewag
drewag

Reputation: 94683

You are getting that error because myLbl is nil.

That is because you are not creating your cell using your Nib. You are using init with style. What you should do, is register the nib with the table view and then use deque on the tableview:

override func viewDidLoad() {
    var cellNib = UINib(nibName:"ANibName", bundle: nil)
    self.tableView.registerNib(cellNib, forCellReuseIdentifier: "default")
}

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{
    var cell = tableView.dequeueReusableCellWithIdentifier("default", forIndexPath: indexPath) as CutomCell
    cell.SetValue(stringArray[indexPath.row])
    return cell;
}

If, however, you are creating template cells in the Nib for your view controller, you don't have to register the seperate Nib for the cell but you still need to deque the cell like above.

Upvotes: 1

Related Questions