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
Take outlet of the Height Constraint of the parent view and assign it the height of table view's content + constant(extra height of other contents in the view)
heightConstraintView.constant = tableView.contentSize.height + constantValue //use the value of constant as required.
and write this code in the cellForRowAt method.
You can change the UITableView height as per the contentSize as below:
Swift 2.2
tableView.frame = CGRectMake(tableView.frame.origin.x, tableView.frame.origin.y, tableView.frame.size.width, tableView.contentSize.height)
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)
and make sure you write the above line in viewDidAppear
method
You need to write the above line in viewDidLayoutSubviews
also.
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()
}
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()
}
DispatchQueue.main.async {
var frame = tableView.frame
frame.size.height = tableView.contentSize.height
tableView.frame = frame
}
OR
DispatchQueue.main.async {
self.TblViewHeightConstraint.constant = CGFloat((self.array.count) * 30)//Here 30 is my cell height
self.TblView.reloadData()
}