自定义和动态内容UITableViewCell

时间:2016-02-13 00:03:56

标签: ios objective-c uitableview autolayout

我已经实现了一个自定义的UITableViewCell(以编程方式)。这里有一点我的代码:

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {

    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
      // Here I initialize three labels with 2 vertical constraints between each other
    }

    return self;
}

当我启动我的应用程序时,我可以看到:

My label 1

|-vertical constraint-|

My label 2

|-vertical constraint-|

My label 3

当我的三个标签有文字时,一切都很好,但有些文章可能没有文字,我的应用程序会显示:

My label 1

|-vertical constraint-|

|-vertical constraint-|

My label 3

所以我需要删除或不初始化相关标签并添加/删除正确的约束来显示:

My label 1

|-vertical constraint-|

My label 3

我必须在哪里这样做?我无法在initWithStyle中执行此操作,因为我不知道我的标签文本是否还有值:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

     MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCustomCell"];
    cell.name.text = name;
    cell.username.text = username;
    cell.description.text = description;

    return cell
 }

提前致谢。

1 个答案:

答案 0 :(得分:0)

您应该有一个包含名称,用户名和描述的模型类,您可以通过configureWithModel:之类的方法将该模型注入到单元格中。 然后在单元格中,您可以动态创建标签。 在您的情况下,我认为您可以在单元初始化程序中创建标签,并且在注入模型时,您只需检查模型的哪些属性可用,您可以隐藏一些标签。 如果您采用这种方法,我建议您实施prepareForReuse并再次显示标签,否则当重复使用单元格时,以及之前隐藏的标签可能会在您不想要时显示隐藏这一点。

相关问题