Anand Gautam
Anand Gautam

Reputation: 2579

How to set dynamic table height based on table row?

I am facing table height issue at run time.

I have a Scroll View added to my Super view. Over the Scroll View, I have added a UIView in the top then after UIView I have placed one UITableView (scrollEnabled false) and again have added a UIView in the bottom of my UITableView.

Problem: I want user to do a single scroll in the screen, so I have disabled table view scrolling property. Now my problem is I am fetching table array data from server so after getting data from server, my viewDidLayoutSubviews method is not getting called where I have wrote the table height logic. And when I am re-loading the same screen then everything is working fine.

Here is my code :

override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        if devicesArray.count != 0{
            viewDeviceList.frame = CGRect(x: viewDeviceList.frame.origin.x, y: viewDeviceList.frame.origin.y, width: viewDeviceList.frame.size.width, height: tableDeviceList.contentSize.height)

            tableDeviceList.reloadData()
        }

    }

Can anyone suggest me on this. Thank you.

Upvotes: 0

Views: 335

Answers (2)

Gowri G
Gowri G

Reputation: 420

Create outlet for tableView height constraint like this

@IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint!

add this line

self.tableView.reloadData()
self.tableViewHeightConstraint.constant = self.tableView.contentSize.height

Upvotes: 0

Abdul Hoque Nuri
Abdul Hoque Nuri

Reputation: 1097

Please try with below code and let me know. I'm working with observer and its working perfectly.

//MARK:- Add this observer into your View/Controlloer
        override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            self.transactionTableViewHeightConstraints.constant = transactionTableView.contentSize.height
        }
//MARK:- Fetch TableListData
    func updateTableViewHeightAfterAPICall(){
            self.transactionTableView.addObserver(self, forKeyPath: "contentSize", options: [], context: nil)
            self.transactionTableView.reloadData()
            UIView.animate(withDuration: 0.5) {
                self.view.layoutIfNeeded()
            }
        }

Upvotes: 0

Related Questions