Matias
Matias

Reputation: 551

2 custom UITableViewCell in one UITableView Swift

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.

Upvotes: 2

Views: 1003

Answers (1)

Selva Murugan
Selva Murugan

Reputation: 11

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

Upvotes: 1

Related Questions