Adding UILabel to a custom tableViewCell programmatically

Viewed 2151

I'm trying to add a label programmatically to a custom table view cell. The app will still crash with an 'unexpectedly found nil'. I've looked into other posts here but I can't see what I'm doing wrong. Please see the code for details.

import UIKit

class MyTableViewCell: UITableViewCell {

  var titleLabel: UILabel!

  override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    titleLabel = UILabel()
    titleLabel.textColor = UIColor.blackColor()
    titleLabel.font = UIFont.systemFontOfSize(17)
    titleLabel.frame = CGRect(x: 40.0, y: 2, width: bounds.width, height: bounds.height)
    addSubview(titleLabel)
  }

  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
  }

}

Inside the view controller:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! MyTableViewCell
    // Crashes the app with: 'fatal error: unexpectedly found nil while unwrapping an Optional value'
    cell.titleLabel.text = "Some text"
}

The custom table view class is properly assigned to the prototype cell in the storyboard.

If I change the declaration inside MyTableViewCell to var titleLabel = UILabel() and delete that line from inside the init() the table view will display but my label will not show up. The code looks good to me though, any advice as to what I may be missing here?

1 Answers
Related