2016-02-13 65 views
0

我已经实现了一个自定义的UITableViewCell(以编程方式)。在这里我的代码一点点:自定义和动态内容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 
} 

感谢。

回答

0

您应该有一个名称,用户名和说明的模型类,您可以通过像configureWithModel:这样的方法将该模型注入单元。 然后在单元格中,您可以动态创建标签。 在你的情况下,我认为你可以在单元格初始值设定项中创建标签,当注入模型时,只需检查模型的哪些属性可用,并且可以隐藏一些标签。 如果你采用这种方法,我建议你实现prepareForReuse并使标签再次可见,否则当一个单元格被重复使用,并且以前隐藏的标签可能会在你不需要时隐藏它。

+0

听起来不错。我会试试看。 –

+0

我在哪里可以添加/更新我的约束? –

+0

在注入模型的配置方法中。 –

相关问题