林很新的iOS開發,我一直在堅持這幾天動態設置的UIScrollView與UITableView的高度由它的內容
我有一個UIScrollView
內UITableView
和UIImageView
,在UIImageView
在頂部的表和高度是靜態的,所以我沒有任何問題,這個問題是UITableView
,我需要根據內容動態獲取高度,並將該高度設置爲表的高度約束和內容的scrollview。
這些單元格是自我大小的,所以單元格的高度根據內容而不同。我能做到的最好的辦法是使用的contentSize.height
財產獲得高度,但顯然這會返回基於我設置的estimatedRowHeight
的高度,而不是每行的實際高度。
代碼:
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.estimatedRowHeight = rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
tableView.layoutIfNeeded()
tableHeight.constant = tableView.contentSize.height
scrollView.contentSize.height = imageView.bounds.height + tableView.contentSize.height
}
我已經試過:
- 通過使用
UITableView
contentSize.height
財產獲得的高度,如圖中的代碼和之前解釋。 獲取每個行的高度,分別在
willDisplayCell
上,並將其添加到表格的高度約束和scrollview的contentSize中。但看起來這樣會增加更多的行數,給我一些表格末尾的空單元格。內部willDisplayCell
的代碼:let cellHeight = cell.bounds.height tableHeight.constant += cellHeight scrollView.contentSize.height += cellHeight
的以前一樣,除了i以外具有相同的結果內
cellForRowAtIndexPath
試過。
第一個問題,爲什麼在滾動視圖內使用一個表(它有一個內置的滾動視圖)(並設置高度來取消表的滾動功能)?其次,爲了做你所要求的,你將需要在for循環中手動調用'cellForRoAtIndexPath'遍歷你的表數據。然後獲取從該函數返回的每個單元格的高度,併合並所有高度以獲得全局表格高度。但是我回到第一個問題,爲什麼要重做已經爲你做的事情(在scrollview中滾動的表)? – Putz1103
**訪問此內容爲您的答案** http://stackoverflow.com/questions/5628527/dynamically-set-uiscrollview-height-and-uitableview-height-depending-on-content –