I'm trying to load dynamic nibs as subviews of containers. I almost got it to work, except that the subviews have an offset I can't seem to get rid off (cf pink view in pictures below).
From the View Hierarchy debugging:
As you can see in 2nd picture, the container frame is correctly positioned, whereas the subview isn't, for some reason.
I don't really know what is going with autolayout.
Here's the code that deals with loading the nib and assigning it as subview:
The commented-out code is all the things I've tried to make it work, with no success. I thought autolayout would work on its own without me having to do anything, but by default it loads the nib without resizing it.
That means the leading and top anchors are correct, however the nib then uses its full size... (cf picture below)
So the question is, what is needed for me to do in order to load the nib and make it fit to the container view ?
You should add constraints to your NibView instead of setting the bounds and the frame of the NibView.
Try to call the following function (addFullScreenConstraint) on the NibView after adding the NibView as a subview of the content view:
extension UIView {
/// Adds constraints to this `UIView` instances `superview` object
/// to make sure this always has the same size as the superview.
/// Please note that this has no effect if its `superview` is `nil`
/// – add this `UIView` instance as a subview before calling this.
func addFullScreenConstraints() {
guard let superview = self.superview else {
return
}
self.translatesAutoresizingMaskIntoConstraints = false
superview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[subview]-0-|",
options: .directionLeadingToTrailing, metrics: nil, views: ["subview": self]))
superview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[subview]-0-|",
options: .directionLeadingToTrailing, metrics: nil, views: ["subview": self]))
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With