2016-02-13 59 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

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

相關問題