ggworean ggworean - 6 months ago 10
iOS Question

Implementing two UITableViews with the same custom cell for reuse

I have currently have two

UITableView
s populated with contacts for the app. I have one for simply viewing them and editing/deleting and one for searching/picking contacts from a list. However, I'm getting a returned nil value when trying to use the same custom class cell for both
UITableView
s.

These are my two
cellForRowAtIndexPath
functions.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("SecondCell") as! ContactCell
let item = contacts[indexPath.row]
cell.meetupLabel?.text = item.fullName
return cell
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("FirstCell") as! ContactCell
let item = contacts[indexPath.row]
cell.label?.text = item.fullName
return cell
}

Answer

If the table did not have a cell named FirstCell or SecondCell, the dequeueReusableCellWithIdentifier(_:) method will return nil, and you will need to construct the cell yourself.

// no don't do this.
let cell: ContactCell
if let c = tableView.dequeueReusableCellWithIdentifier("FirstCell") as? ContactCell {
    cell = c
} else {
    cell = ContactCell(style: .Default, reuseIdentifier: "FirstCell")
}

You should use dequeueReusableCellWithIdentifier(_:forIndexPath:), which was introduced in iOS 6, if you would like UIKit to construct the cell for you:

let cell = tableView.dequeueReusableCellWithIdentifier("FirstCell",
                forIndexPath: indexPath) as! ContactCell
...

Also, check if you have given the correct reuse-identifiers to the cells correctly in the interface builder.

enter image description here