2015-10-06 100 views
7

我有一個靜態的UITableView,它有12行和11行,我知道高度需要。靜態UITableView,在Swift中製作一個具有動態高度的單元格

我有一個UILabel,其中有坐在12行內的動態文本,我如何去製作基於UILabel中文本的動態高度。

我試過viewDidLoad以下的代碼,但它沒有奏效。行保持相同的高度。我還設置線= 0UILabel

tableView.estimatedRowHeight = 100.0 
    tableView.rowHeight = UITableViewAutomaticDimension 
+0

請解釋您的意思是「它沒有工作」。瞭解您已經實施的「UITableViewDelegate」中的哪些相關方法以及如何實現也很重要。 –

回答

9

您試過嗎?

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
    if (indexPath.row < 11) { 
     // Everything starts at 0, so this covers 0-10 
     // Whatever your cell height is 
     return <#fixedCellHeight#> 
    } else { 
     // This is your 12th cell (indexPath.row 11), as we start counting at 0 
     return UITableViewAutomaticDimension 
    } 
} 
+1

在有望重回「CGFloat的」 –

+0

一個功能缺失的回報,我改變它周圍的,如果(indexPath.row <11){ 回100 }其他{ 回報UITableViewAutomaticDimension }好像它的工作,我怎樣才能改變上述爲零而不是100 –

1

試試這個:

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
    return UITableViewAutomaticDimension 
} 
0

您可以創建2個電池原型細胞的表視圖。你給他們2個不同的ID。 然後在您的代碼中,您覆蓋此功能

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    var cell = UITableViewCell() 

    if indexPath.row < 12 { 
     cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) 
    } else { 
     cell = tableView.dequeueReusableCellWithIdentifier("cell12", forIndexPath: indexPath) 
    } 

    return cell 
} 
0

您可以創建文本高度動態小區,那麼你可以設置表視圖

此處的靜態和動態的細胞都在鏈接到動態細胞與文本如何動態地更改單元格高度的UITableView靜態單元格

0

如果您使用的是靜態單元格,將一個單元格更改爲動態高度,並且其他人可以編輯爲此,則可以添加@Adrian答案。

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 

     if indexPath.row == 11 { 
     // This is your 12th cell (indexPath.row 11), as we start counting at 0 
      return UITableViewAutomaticDimension 
     } else { 
      return super.tableView(tableView, heightForRowAtIndexPath: indexPath) 
     } 
    } 
0

更優雅可能是剛剛實施的建議:

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
    return UITableViewAutomaticDimension 
} 

或者在目標C:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    return UITableViewAutomaticDimension; 
} 

但是,而不是行特定的邏輯,加約束你的靜態細胞的內容在Storyboard保持行高不變。這樣,如果您移動行或更改內容,則無需更改任何代碼。

相關問題