This is my Swift code to generate my table view. I am trying to set up a tableView with detail labels. The problem is that the following code is never called.
if (cell == nil) {
println("1")
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "CellSubtitle")
//cell = tableViewCell
}
Here is the code you need for the method:
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
println("start TableViewCellForRowAtIndexPath")
var cell: UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("CellSubtitle", forIndexPath: indexPath) 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?
You don't need to check if the cell is nil using this dequeue method, as long as you've register a cell class for reuse, or provided a prototype in Interface Builder.
let cell = tableView.dequeueReusableCellWithIdentifier("CellSubtitle", forIndexPath: indexPath) as! UITableViewCell
If however, you want to continue manually initializing the cells, you can use the following dequeue method instead. (keep in mind, this is the old way)
let cell = tableView.dequeueReusableCellWithIdentifier("CellSubtitle") as? UITableViewCell
Then as far as initializing the detailTextLabel goes, you don't have to. It's built into the cell, and by specifying that the cell's style should be subtitle, that label will be set up for you.
Note that the casts aren't necessary in Swift 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With