通过数量或行数设置TableView的高度 [英] Set TableView height by the number or rows
问题描述
我在MainstoryBoard
中有TableView
,并且行数每次都是随机的.
我希望整个TableView
的高度灵活-例如,如果我在TableView
中有4行,而每个TableView
行高为22,则TableView
高度将为88 .
另一个例子:
行数:2
行高= 22
TableView
将为44.
I have got TableView
in the MainstoryBoard
and the number of rows is random every time.
I want the height of the whole TableView
to be flexible - by that I mean, for example: if I got 4 rows in the TableView
and each TableView
row height is 22 so the TableView
height will be 88.
Another example:
number of rows: 2
row height = 22
TableView
will be 44.
我该怎么做?
推荐答案
您可以根据contentSize更改UITableView的高度,如下所示:
You can change the UITableView height as per the contentSize as below:
Swift 2.2
Swift 2.2
tableView.frame = CGRectMake(tableView.frame.origin.x, tableView.frame.origin.y, tableView.frame.size.width, tableView.contentSize.height)
快速3或4 +
Swift 3 or 4+
tableView.frame = CGRect(x: tableView.frame.origin.x, y: tableView.frame.origin.y, width: tableView.frame.size.width, height: tableView.contentSize.height)
并确保您在viewDidAppear
方法中写以上行
and make sure you write the above line in viewDidAppear
method
您还需要在viewDidLayoutSubviews
中写上一行.
You need to write the above line in viewDidLayoutSubviews
also.
Swift 2.2
Swift 2.2
func viewDidLayoutSubviews(){
tableView.frame = CGRectMake(tableView.frame.origin.x, tableView.frame.origin.y, tableView.frame.size.width, tableView.contentSize.height)
tableView.reloadData()
}
快速3或4 +
Swift 3 or 4+
func viewDidLayoutSubviews(){
tableView.frame = CGRect(x: tableView.frame.origin.x, y: tableView.frame.origin.y, width: tableView.frame.size.width, height: tableView.contentSize.height)
tableView.reloadData()
}
这篇关于通过数量或行数设置TableView的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!