2017-07-16 70 views
0

我有一個UITableView。在我的tableview中,我想動態添加另一個視圖到我的單元格中,並擴大單元格高度。我看到了一些例子,但是這些例子是UILabels。 UILabels可以根據文本高度更改高度。但我怎麼手動添加另一個視圖並展開這些單元格?如何動態擴展UITableViewCell高度?

請幫我 感謝

回答

0

如果使用手動計算單元格的高度,它很容易,你加入另一個視圖後,你計算的高度,然後調用reloadData或reloadRowsAtIndexPaths,並在tableview中返回的高度: heightForRowAtIndexPath函數。 如果你使用自動計算單元格高度,你應該讓系統知道如何計算,你應該清楚和完全地設置自動佈局。你應該添加另一個視圖的左,右,上,下約束,系統將自動可以調整高度。因此細胞將會擴大。

+0

謝謝,,爲table.rowheight我應該設置默認大小還是將其設置爲動態? – user1960169

+0

你可以像這樣設置:self.tableView.estimatedRowHeight = 100; //像所有單元一樣的值 self.tableView.rowHeight = UITableViewAutomaticDimension; – zacks

0

您可以通過覆蓋設置單元格的高度func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat

0

實現這兩個的UITableViewDelegate方法:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
    return UITableViewAutomaticDimension 
    } 

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { 
    // return estimatedHeight 
    } 

查看在動態細胞需要有頂部,底部,尾隨,領導和高度的限制。設置視圖高度約束常數將根據視圖高度設置單元高度。

您可以查看高度約束屬性在動態細胞:

@IBOutlet weak var customViewHeightConstraint: NSLayoutConstraint! 

約束恆定值,可以在cellForRowAt改變:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "CellId", for: indexPath) as! Cell 

    switch indexPath.row { 
    case 0: 
     cell.customViewHeightConstraint.constant = 100 
    case 1: 
     cell.customViewHeightConstraint.constant = 200 
    case 2: 
     cell.customViewHeightConstraint.constant = 300 
    case 3: 
     cell.customViewHeightConstraint.constant = 400 
    default: 
     cell.customViewHeightConstraint.constant = 100 
    } 

    return cell 
} 
+0

我這樣做,如果(arraycontainsthisvalue)然後更改heigt = 100其他高度= 50。但有時它在錯誤的情況下給了我錯誤的高度,它仍然給我100爲什麼是這樣? – user1960169