I'm working on a project in Swift 3.0 and it has a UITableView inside a UIScrollView that has already been set its constraints.
The requirement is to display a list of songs that would return from an array in this UITableView, but the size of this UITableView should dynamically arrange according to the size of the array, so I do not need to scroll the UITableView since I can see all the songs in the UITableView (this UITableView is inside my scrollView, so instead I can use my scrollView do move up or down the list).
How would I achieve this?
You can change height of the tableview based on the content.
var frame = tableView.frame
frame.size.height = tableView.contentSize.height
tableView.frame = frame
If you are using autolayout create outlet for tableview height and assign tableview content size to its constant.
tableviewHeightConstraint.constant = tableview.contentSize.height
1.Create a subclass for tableView and override intrinsicContentSize.
class MyOwnTableView: UITableView {
override var intrinsicContentSize: CGSize {
self.layoutIfNeeded()
return self.contentSize
}
override var contentSize: CGSize {
didSet{
self.invalidateIntrinsicContentSize()
}
}
override func reloadData() {
super.reloadData()
self.invalidateIntrinsicContentSize()
}
}
2. In Interface builder change the class of your tableView to MyOwnTableView (subclass of UITableView).
Set automatic row height for the table view.
tableView.estimatedRowHeight = 60.0
tableView.rowHeight = UITableViewAutomaticDimension