2

I am trying to implement a custom table view which has different types of cells: type A and type B. All of my cells should be of type A, except for one that will be of type B. Whenever the users selects a cell, this one changes to type B.

My code is the following one:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let row = indexPath.row
    if (row == typeBCellIndex) {
        // Get Type B cell
        let cell = tableView.dequeueReusableCellWithIdentifier(typeBCellIdentifier, forIndexPath: indexPath) as! TypeBTableViewCell
        return cell
    } else {
        // Get Type A cell
        let cell = tableView.dequeueReusableCellWithIdentifier(typeACellIdentifier, forIndexPath: indexPath) as! TypeATableViewCell
        cell.detailLabel.text = "I am a type A cell"
        return cell
    }
}

The variable typeBCellIndex is initialised in 0, and this code gives an error when I add a new cell and try to dequeue the cell at index 1.

In Objective-C, as this links indicates, I would check if the cell is nil, and if not create a new instance of the corresponding cell. However, I am not sure if this concept applies to Swift, and in case it does, I don't know how to do it.

Community
  • 1
  • 1
Matias
  • 541
  • 5
  • 22
  • Hope you have correctly registered a class or nib file using the registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier: for both types. – Shripada Sep 18 '15 at 05:12
  • @Shripada I have registered both classes in viewDidLoad() method. The error is "fatal error: unexpectedly found nil while unwrapping an Optional value" when doing `cell.detailLabel.text = "I am.."` for row=1. – Matias Sep 18 '15 at 13:06

1 Answers1

1

declare a variable cellindex before viewdidload method and initialize to 3 or any number

and in tableview design two different cells and assign unique identifier for each

code for tableview is

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    var cell : UITableViewCell!
    var row = indexPath.row

    if(row == cellindex){
        cell = tableView.dequeueReusableCellWithIdentifier("Cell2", forIndexPath: indexPath) as! UITableViewCell
    }else{
        cell = tableView.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath) as! UITableViewCell
    }

    return cell
} 

the cellindex row will be cell2 and other cells are cell1

  • The problem is that I must cast the cell as TypeATableViewCell, since I want to modify data (detailLabel in the example) that is not available in a UITableViewCell. – Matias Sep 18 '15 at 13:03