简体   繁体   中英

How to Update TableView and its parent ScrollView Height according to its content

I have a UITableView that is set to not enable scrolling, and it exists in a UIScrollView . I'm doing it this way as the design specs call for something that looks like a tableView . The TableView Cell having dynamic height So I use

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return UITableViewAutomaticDimension
}

Now once I fetched data from API and before Reloading TableView.

I update height constraint of both tableView and ScrollView . But height does not get update. I used the below code

self.view.layoutIfNeeded()
tvHeightConstraint.constant = tvPrdtDetail.contentSize.height
svHeightConstraint.constant = tvPrdtDetail.contentSize.height + 8

Here tvHeightConstraint and svHeightConstraint are height constraint of tableView and ScrollView

@IBOutlet weak var tvHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var svHeightConstraint: NSLayoutConstraint!

Log always show 0 when I print TableView ContentSize

  print("Content Size: \(tvPrdtDetail.contentSize.height)")

Please help me out . Thanks in advance.

Re order like this as call to layoutIfNeeded should be after updating the constants of the constraints

tvHeightConstraint.constant = tvPrdtDetail.contentSize.height 
svHeightConstraint.constant = tvPrdtDetail.contentSize.height + 8  //  remove this 
self.view.layoutIfNeeded()

Also no need for 2nd line as if you hook constraints properly in the scrollview from top to bottom updating height constraint of the table will update the scrollview

Edit:

1- give the table height constraint say 3000 ( some big number ) followed by self.view.layoutIfNeeded()

2- reload the table

3- get the y frame of the last cell

4- assign it to the height constraint

5- layout the view

do this after you get the data

Try this hope so this will work.Call this when you need constraint should update,And override updateConstraints function

self.layoutIfNeeded()

override public func updateConstraints() {
    super.updateConstraints()
    tvHeightConstraint.constant = tvPrdtDetail.contentSize.height
    svHeightConstraint.constant = tvPrdtDetail.contentSize.height + 8
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM