Diogo Martins Diogo Martins - 5 months ago 11
iOS Question

Constraints not respected when loading from XIB

So, I have the following XIB

enter image description here

This XIB when loaded as a tableviewcell looks like this

enter image description here

I've since decided that I will not need a TableView, so I changed my XIB class from UITableViewCell to UIView. In a ViewController I added this code to viewDidLoad()

var nView = MyChartView.instanceFromNib() as! MyChartView
self.view.addSubview(nView)


And I got this as a result

enter image description here

As you can see, it ignores the margins and continues to right side (ignore the red color since I was using it to try and debug the problem. No chart data is not the problem either). I've printed the xib's frame width and I've seen that it's quite a bit bigger than the screen size, but I've not been able to fix it. Anyone can figure out the problem?

Answer

When you add a subView programmatically, you should also add constraints between the subView and its superView

var nView = MyChartView.instanceFromNib() as! MyChartView
self.view.addSubview(nView)
nView.translatesAutoresizingMaskIntoConstraints = false
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[nView]|", options:  [], metrics: nil, views: ["nView": nView]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[nView]|", options: [], metrics: nil, views: ["nView": nView]))
Comments