Consider the following simple view controller:
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var items = ["One", "Two", "Three"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "customCell")
self.tableView.dataSource = self
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("customCell") as CustomTableViewCell
cell.titleLabel!.text = self.items[indexPath.row]
return cell
}
}
And custom cell view:
class CustomTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
}
This code causes the following error.
fatal error: unexpectedly found nil while unwrapping an Optional value
titleLabel
is nil — it's not clear why. Setting default properties of UITableViewCell
(like textLabel
) work just fine.
I'm using a nib for the custom cell.
Both the labels and table views are correctly connected to their IBOutlet
s.
Both the prototype cell and the custom nib view are marked as having a CustomTableViewCell
class.
I'm new to iOS development, am I missing something obvious?
cell
is not nil. For example, setting the cell'stextLabel
property causes the label to correctly appear in the UI. – David Chouinard