Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) ?

like image 972
Rob Avatar asked Nov 28 '22 11:11

Rob


2 Answers

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
}
like image 59
Anupdas Avatar answered Dec 29 '22 06:12

Anupdas


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 **/
        }
}
like image 20
Kunal Kumar Avatar answered Dec 29 '22 05:12

Kunal Kumar