Search code examples
iosswiftuitableviewconstraintsnslayoutconstraint

Why is Child Table View not sizing properly?


First off, please do not propose a "clever" solution suggesting I remove my TableViewController as a child view. Thank you.

Summary

I am adding a Tableviewcontroller programatically , as a child of a view with a fixed size of 216. I have been messing with constraints....and using the View Hierachy Debugger, I see the TableView always has a height of 852...which is basically the full size of the screen. How can I properly size the TableView to its containing view?

enter image description here

Below is a bunch of the code I am trying to use to constrain things...to no avail. Thank you.

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var xyz: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let child = UITableViewController()
        xyz.addSubview(child.view)
        self.addChild(child)
        child.didMove(toParent: self)
        
        //child.view.translatesAutoresizingMaskIntoConstraints = false
        let safeArea = xyz.layoutMarginsGuide

        
        var height = child.view.heightAnchor.constraint(equalToConstant: 292)
        height = height.constraintWithMultiplier(2000)
        height.isActive = true
        
        
        child.view.topAnchor.constraint(equalTo: safeArea.topAnchor).isActive = true
        child.view.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor).isActive = true
        
        child.view.leftAnchor.constraint(equalTo: safeArea.leftAnchor).isActive = true
        child.view.rightAnchor.constraint(equalTo: safeArea.rightAnchor).isActive = true
    }
    
}

extension NSLayoutConstraint {
    func constraintWithMultiplier(_ multiplier: CGFloat) -> NSLayoutConstraint {
        return NSLayoutConstraint(item: self.firstItem!, attribute: self.firstAttribute, relatedBy: self.relation, toItem: self.secondItem, attribute: self.secondAttribute, multiplier: multiplier, constant: self.constant)
    }
}

Solution

  • Uncomment this line of code

    child.view.translatesAutoresizingMaskIntoConstraints = false