Rob
Rob

Reputation: 16002

How can I get the class (custom) of cell selected in UITableView?

Usually I get my selected cell this way:

- (void)tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell *cell = (CustomCell*) [table cellForRowAtIndexPath:indexPath];
}

But in the code I'm working with, I may have many kind of cells in my table view. How can I get the class of my selected cell (if it's for example CustomCell or CustomCell2) ?

Upvotes: 3

Views: 7852

Answers (2)

Kunal Kumar
Kunal Kumar

Reputation: 1722

SWIFT 4

Just in case, if someone needed it. Get the instance of selected cell and then check it for required tableViewCell type.

   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let cell = myCustomCell.cellForRow(at: indexPath)
            else
        {
            return
        }

/** MyCustomCell is your tableViewCell class for which you want to check. **/

    if cell.isKind(of: MyCustomCell.self) 
        {
           /** Do your stuff here **/
        }
}

Upvotes: 9

Anupdas
Anupdas

Reputation: 10201

You can check the type of cell returned

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if ([cell isKindOfClass:[CustomCell class]]) {
     //do specific code
}else if([cell isKindOfClass:[CustomCell2 class]]){
    //Another custom cell
}else{
    //General cell
}

Upvotes: 22

Related Questions