Search code examples
iosswiftuitableviewxib

Swift - Dynamically set UITableView height in Xib


I try to set tableView height with dynamically in Xib. But all elements change dynamically in the xib view and I didn't reach "y" position of the last element before tableview.

I tried something like this but it didn't work.It shows on the top of mainView.

techTableView = mainView?.technicalTableView

self.techTableView?.frame = CGRect(
    x: 0,
    y: (self.techTableView?.topAnchor.constraint(equalTo: (mainView?.productInformation.bottomAnchor)!, constant: 25).constant)! ,
    width: self.view.frame.size.width,
    height: 35)

Solution

  • Use layout anchors to set the constraints instead of setting the frame. You can do something like this to set your tableview's constraints:

    techTableView.translatesAutoresizingMaskIntoConstraints = false
    
        techTableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        techTableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
        techTableView.topAnchor.constraint(equalTo: mainView.bottomAnchor).isActive = true
        techTableView.heightAnchor.constraint(equalToConstant: 35).isActive = true