0
votes

I created a custom UIView based on a xib file and added some UIVIews with constraints.

In my View Controller I added a UIView and set the class to my custom view. So far so good. My custom View is displayed properly.

But now I do have a @IBInspectable (numerOfButtons: Int) and based on this number I want to add UIButtons programmatically to my custom view. My problem is now, that I want to align this buttons to a subview in my custom view. So I try to set my button frames programmatically. But when I do this in layoutSubviews() my subviews are not calculated based of my auto layout constraints. I tried to call setNeedsLayout() and layoutIfNeeded() of my subview but this does not work.

How can I get the correct frames of my subviews (with calculation of my constraints) to work with them in layoutSubviews()

Or what do I wrong?

By the way. It seems that my approach does not works only if I try to run with iPad Pro 9.7 inch simulator?!

1
instead of calculating the frames yourself you should make use of stack views. It would be worthy watching this developer.apple.com/videos/play/wwdc2015/218 and this developer.apple.com/videos/play/wwdc2015/219Leo Dabus
this does not solve my problem because the buttons are not the only controls I want to add based of numberOfButtons. I also want to change the contentSize of a scroll view and add views to this scrollview. And there I cannot use stack views. Thats the reason why I try to figure out how to get the calculated frames.nets-rac

1 Answers

-1
votes

To set constraint programmatically will be time consuming thing but luckily we have an alternative solution with this library very easy to set constraint

    let box = UIView()
    self.view.addSubview(box)
    box.snp.makeConstraints { (make) -> Void in
       make.width.height.equalTo(50)
       make.center.equalTo(self.view)
    }

Hope this will help you