Brosef Brosef - 5 months ago 27
Swift Question

UITableView with two custom cells not appearing properly

I have a grouped tableview that consists of two rows and each row has a custom tableview cell. I have the custom tableview classes and cell identifiers all established and associated with the tableview rows in interface builder. My first tableview cell appears fine, but the second one seems to have the same properties as the first cell. However, once I tap the second cell then tap the first cell, the second cell switches to the correct cell design.

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

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("EditCellID", forIndexPath: indexPath) as! EditCell
if indexPath.row == 0
{
//Do some stuff
return cell
}
if indexPath.row == 1
{
let cell = tableView.dequeueReusableCellWithIdentifier("DeleteCellID", forIndexPath: indexPath) as! DeleteCell
//Do some stuff
return cell
}

return cell
}

Answer

Try this:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell: UITableViewCell!

    if indexPath.row == 0 {
        cell = tableView.dequeueReusableCellWithIdentifier("EditCellID", forIndexPath: indexPath) as! EditCell
        // Now you can access the subclass attributes by doing : (cell as! EditCell).theAttribute
    } else {
        cell = tableView.dequeueReusableCellWithIdentifier("DeleteCellID", forIndexPath: indexPath) as! DeleteCell
    }

    return cell
}

Create only one cell object in scope and, depending on the row, initialize the object as an instance of one your specific UITableViewCell subclasses.

UPDATE: Added a comment on how to access the UITableViewCell subclass attributes.