如何访问多个自定义tableviewcells中的属性

我创build了两个自定义TableViewCells,并成功地向UITableView注册它们。

他们都有不同的属性。 问题是,我如何访问这些属性?

NSDictionary *dict = self.tblContent[indexPath.row]; NSString *identifier; if ([dict[@"type"] isEqualToString:@"type1"]) { identifier = @"cell1"; }else if ([dict[@"type"] isEqualToString:@"type2"]) { identifier = @"cell2"; } CustomCell1 *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; cell.lblWho.text = dict[@"name"]; cell.lblWhen.text = dict[@"date"]; if ([dict[@"type"] isEqualToString:@"type2"]) { (CustomCell2 *)cell.specialField.text = @"special field"; } 

两个单元格都有一个lblWho和一个lblWhen ,但是只有cell2有specialField 。 当我尝试访问它时,XCode抱怨CustomCell1没有属性specialField (当然)。 正如你所看到的,我试图将单元格转换为CustomCell2 ,但这不起作用。

我该如何设置单元格才能访问单元格特有的属性?

在这种情况下最好的办法是(imo):

  1. 创buildMyCell(从UITableViewCellinheritance)。
  2. @interface CustomCell2 : UITableViewCell更改为@interface CustomCell2 : MyCell
  3. 将公共属性移到MyCell
  4. MyCellMyCell函数并在子类中实现它

(void)configureCellForDictionary:(NSDictionary *)dict

并使用它:

 MyCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; [cell configureCellForDictionary:dict] 

使用这种方法,您将隐藏细胞如何将其内容显示到单元格类的细节,您可以将所有常见代码移动到单元格的超类

更多的结构化数据阅读有关使控制器更轻薄 : 更轻的视图控制器和清洁表视图代码

问题在于演员的优先级。 这一行:

 (CustomCell2 *)cell.specialField.text = @"special field"; 

铸造比你想要的更多。 尝试更合格:

 ((CustomCell2 *)cell).specialField.text = @"special field"; 

顺便说一句@NikitaTook给出了关于devise的一个很好的答案。 按单元格types分解代码。 但更直接的问题是演员。

对于后代来说,普通的超类避免了演员问题,但并不总是谨慎或可能的。 以下是一般处理条件types的方法。

 // declare the variable in question as the lowest common ancestor on // the class hierarchy, use id when the variable can be any class // for this problem, we know they are UITableViewCells at least... UITableViewCell *cell = [tableView dequeue... // add a conditional that determines the type. In this case, the // kind of cell we want is based on the model, but this can be any condition... if ([dict[@"type"] isEqualToString:@"type1"]) { // declare a new local of the now-known, more specific type. // initialize it with a cast of the abstractly declared instance MyTableViewCellSubtypeA *cellTypeA = (MyTableViewCellSubtypeA *)cell; NSLog(@"%@", cellTypeA.propertySpecificToA); // use it specifically // if you're lazy, or just have a one-liner, cast as I suggest, using parens properly (MyTableViewCellSubtypeA *)(cell).propertySpecificToA; 

相同的想法为其他分支。

  1. 你可以检查单元的类:

     if ([cell isKindOfClass: [CustomCell1 class]]) { //Customize customcell1 } else { //Customize customcell2 } 
  2. 你可以检查你的单元格是否有“specialField”属性:

     if ([cell respondsToSelector: @selector(specialField)]) { //Custom cell 2 } else { //Custom cell 1 }