如何在UITableView中选择单元格的类(自定义)?

Rob*_*Rob 3 uitableview ios

通常我这样选择我的选定单元格:

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

但是在我正在使用的代码中,我的表视图中可能有很多种单元格.如何获取所选单元格的类(如果是CustomCell或者CustomCell2)?

Anu*_*das 17

您可以检查返回的单元格类型

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
}
Run Code Online (Sandbox Code Playgroud)


Kun*_*mar 8

快速 4

以防万一,如果有人需要它。得到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 **/
        }
}
Run Code Online (Sandbox Code Playgroud)