Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make subview fit inside container and resize correctly

Tags:

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).

enter image description here

From the View Hierarchy debugging:

enter image description here

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:

enter image description here

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)

enter image description here

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 ?

like image 358
Skwiggs Avatar asked Jul 10 '17 10:07

Skwiggs


1 Answers

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]))
    }
}
like image 171
cb89 Avatar answered Oct 11 '22 14:10

cb89