我创建了两个自定义 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) 是:
- 创建 MyCell(继承自
UITableViewCell
)。 - 将
@interface CustomCell2 : UITableViewCell
更改为@interface CustomCell2 : MyCell
- 将通用属性移动到
MyCell
- 在
MyCell
中创建函数并在子类中实现
(void) configureCellForDictionary:(NSDictionary *) dict
并使用它:
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
[cell configureCellForDictionary:dict]
使用这种方法,您将隐藏单元格如何向单元格类显示其内容的细节 + 您可以将所有公共(public)代码移动到单元格的父类(super class)
有关使 Controller 更薄的更多结构化数据阅读: Lighter View Controllers和 Clean table view code
关于ios - 如何访问多个自定义表格 View 单元格中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24913851/