ios - 如何访问多个自定义表格 View 单元格中的属性

标签 ios objective-c xcode uitableview

我创建了两个自定义 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. 创建 MyCell(继承自 UITableViewCell)。
  2. @interface CustomCell2 : UITableViewCell 更改为 @interface CustomCell2 : MyCell
  3. 将通用属性移动到MyCell
  4. MyCell中创建函数并在子类中实现

(void) configureCellForDictionary:(NSDictionary *) dict

并使用它:

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

使用这种方法,您将隐藏单元格如何向单元格类显示其内容的细节 + 您可以将所有公共(public)代码移动到单元格的父类(super class)

有关使 Controller 更薄的更多结构化数据阅读: Lighter View ControllersClean table view code

关于ios - 如何访问多个自定义表格 View 单元格中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24913851/

相关文章:

ios - 自动关闭 UIAlertView 后导航栏色调颜色发生变化

ios - 免费版应用程序和专业版应用程序,复制 Xcode 6 项目?

objective-c - NSFetchedResultsController 帮助

iphone - 如何在iphone中播放MID文件?

xcode - 如何将xcodebuild与-only-testing和-skip-testing标志一起使用?

ios - react native 。 TouchableOpacity 仅在用 2 根手指点击时有效

ios - 如何同步单元格动画

objective-c - 为什么 NSInvocation getReturnValue : lose object?

ios - 无法从存储在 Assets 目录中的文件中获取数据

ios - 在 ios 8.3 及更高版本中,UIAlertView 导致 keyboardWillShow 和 keyboardWillHide 被调用两次