如何创建可以自动调整高度的 table

How to create a table whose height can be autoadjusted

我有一个高度为屏幕 70% 的表格视图,有时我没有足够的行来填满所有 70%,那么在那种情况下会有一些带有空白行的空白区域,它看起来 awkward.so 如果高度自动调整到表格内容,那就太好了,但我找不到与此相关的任何内容。

那么怎么做呢?

你可以像下面那样做

  • IBOutlet 的高度限制 UITableView

你会根据你的 data/rows

找到 tableView 的高度
tableView.contentSize.height

现在您需要根据以下条件更改身高限制

if  tableView.contentSize.height < UIScreen.main.bounds.size.height { // Instead of UIScreen.main.bounds.size.height, change as per your requirment

  yourTblHeightConstraints.constant = tableView.contentSize.height
  self.view.layoutIfNeeded()
}
else {
  yourTblHeightConstraints.constant = UIScreen.main.bounds.size.height // Instead of UIScreen.main.bounds.size.height, change here as you need
  self.view.layoutIfNeeded()
}