[英]iOS Auto-Layout: Dynamic height for table view cell
我有一個包含一堆單元格的表視圖(自定義單元格,只有其內容視圖)。
在tableView:cellForRowAtIndexPath:
我將預定義的UIView(有幾個子視圖)添加到自定義單元格的內容視圖中。 我之前為UIView及其子視圖設置了所有約束。
最后但並非最不重要的是,我為自定義單元格(superview)的內容視圖和之前添加的UIView(子視圖)設置了垂直和水平約束。
約束字符串如下所示:
H:|[view]|
V:|[view]|
不幸的是,我仍然獲得所有表視圖單元格的默認高度。 我想知道是否有辦法讓自動布局根據內容大小自動計算高度。
在這里查看我對這個問題的詳細答案: https : //stackoverflow.com/a/18746930/796419
設置需要一些工作,但是您可以完全使用自動布局約束來驅動完全動態的表視圖而不需要單個硬編碼高度(並且讓約束求解器完成繁重的工作並為您提供行高)。
自動布局無助於單元格高度。 您需要在tableView:heightForRowAtIndexPath
設置它。 我想你可能會問這個因為你的細胞高度是可變的,而不是固定的。 即,它們取決於內容。
要解決此問題,請預先計算單元格高度並將其存儲在數組中。 返回tableView:heightForRowAtIndexPath
方法中相應indexPath
的值。
一定要使用UILabel
類的sizeThatFits
等計算主線程的內容大小。
如果您的計算是密集的,除了與視圖相關的方法(如sizeThatFits
之外,請將其中的大部分工作放在main
。
我通過使用CGSize size = [view systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
解決了這個問題CGSize size = [view systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
在tableView:heightForRowAtIndexPath:
.
要設置行高的自動尺寸,請確保執行以下步驟,自動尺寸對單元格/行高度布局有效。
UITableViewAutomaticDimension
分配給rowHeight和estimatedRowHeight heightForRowAt
並向其返回值UITableViewAutomaticDimension
) 迅速:
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Don't forget to set dataSource and delegate for table
table.dataSource = self
table.delegate = self
// Set automatic dimensions for row height
// Swift 4.2 onwards
table.rowHeight = UITableView.automaticDimension
table.estimatedRowHeight = UITableView.automaticDimension
// Swift 4.1 and below
table.rowHeight = UITableViewAutomaticDimension
table.estimatedRowHeight = UITableViewAutomaticDimension
}
// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// Swift 4.2 onwards
return UITableView.automaticDimension
// Swift 4.1 and below
return UITableViewAutomaticDimension
}
對於UITableviewCell中的標簽實例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.