iOS Question

UITableViewCell doesn't show

i'm creating a simple Table but without storyboard, just coding, currently I can create the table but when I add the cell it crashes, these are my variables:

var optionsTableView:UITableView!
var options = ["Option1", "Option2"]


When I tapped a button the table appears, the function is:

@IBAction func Options(sender: AnyObject) {
if optionsTableView != nil {
optionsTableView.removeFromSuperview()
self.optionsTableView = nil
return
}

self.optionsTableView = UITableView()
self.optionsTableView.backgroundColor = UIColor(white: 0, alpha: 0.95)
self.optionsTableView.delegate = self
self.optionsTableView.dataSource = self
self.optionsTableView.translatesAutoresizingMaskIntoConstraints = false

var constraints = [NSLayoutConstraint]()
constraints.append(NSLayoutConstraint(item: optionsTableView, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1.0, constant: 100.0))
constraints.append(NSLayoutConstraint(item: optionsTableView, attribute: .Trailing, relatedBy: .Equal, toItem: sender, attribute: .Trailing, multiplier: 1.0, constant: 0))
constraints.append(NSLayoutConstraint(item: optionsTableView, attribute: .Top, relatedBy: .Equal, toItem: sender, attribute: .Bottom, multiplier: 1.0, constant: 5.0))

self.view.addSubview(optionsTableView)
self.view.addConstraints(constraints)

optionsTableView.addConstraints([NSLayoutConstraint(item: optionsTableView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: 220.0)])
}


The functions for the table:

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.options.count
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44.0
}


Up to here everything goes well but with the cellForRowAtIndexPath the app crashes:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = optionsTableView.dequeueReusableCellWithIdentifier("cell")!
if tableView == optionsTableView {
cell = UITableViewCell(style: .Default, reuseIdentifier: "cell")
cell.backgroundView = nil
cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.textColor = UIColor.whiteColor()
cell.textLabel?.text = self.options[indexPath.row]
return cell
}
return cell
}


Specifically in this line the app crash:

var cell = optionsTableView.dequeueReusableCellWithIdentifier("cell")!


And console says: "fatal error: unexpectedly found nil while unwrapping an Optional value", what you think is happening??

Answer

That line is crashing is because it isn't finding a cell with that reuse identifier.

You have to register it:

self.tableView.registerClass(Cell.self as AnyClass, forCellReuseIdentifier: "cell")

That way when you force unwrap it won't crash.

Comments