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 fl
Simply take outlet for tableview height constraint and update it in willDisplay cell: UITableViewCell
method of UITableView
@IBOutlet weak var tblHConstraint: NSLayoutConstraint!
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
self.tblHConstraint.constant = self.tblView.contentSize.height
}
Use this for Swift 3
override 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()
}
Note: when your are increasing the tableview height it will goes out side the view. and you will get a problem with scrolling.
Ex: take a view inside that keep tableview and give constraints to left,right,bottom,top to Zero(0).
now reload the tableview assume 2 rows each row height is 20 now total rows height is 40. its fine and gave those height to table view, Table view will show only 40 height (you can assign tableview height by taking constraints (or) table view content size both are give same height according to rows height).
But if you reload 50 rows you will get scrolling problem because those rows height given to table view height, here table view height expands more than your screen height.
To solve this problem you should use scroll view outside the tableview.
nothing worked here is the solution i ended up using which gives accurate height.
extension UITableView {
var contentSizeHeight: CGFloat {
var height = CGFloat(0)
for section in 0..<numberOfSections {
height = height + rectForHeader(inSection: section).height
let rows = numberOfRows(inSection: section)
for row in 0..<rows {
height = height + rectForRow(at: IndexPath(row: row, section: section)).height
}
}
return height
}
}
Usage:
tableView.contentSizeHeight
will give you the actual calculated height of your table view content.
To use with with autolayout:
Somewhere in viewDidLoad()
tableView.anchor(top: view.topAnchor, leading: view.leadingAnchor, bottom: nil, trailing: view.trailingAnchor)
and then in your viewDidLayoutSubViews()
tableView.heightAnchor.constraint(equalToConstant: tableView.contentSize.height).isActive = true
Take outlet of tableview height and set it with your tableview row height in cellForRowAt like this,
tableviewHeight.constant = (tableView.contentSize.height * no_of_rows) + bottom_space