How to set UIView size to match parent without constraints programmatically

Try this

subview.frame = parentView.bounds

subview.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

parentView.addSubview(subview)


May be this will help you

override func viewDidLayoutSubviews() {

    let newView = UIView()
    newView.frame = iBag.bounds
    newView.addConstraints(iBag.constraints)
    newView.backgroundColor = UIColor.redColor()
    iBag.addSubview(newView)

}

Hope this will help you.


So many answers and nobody is explaining what's wrong.

I will try.

You are setting the frame of newView to your superviews frame before the autolayout engine has started to determine your superviews position and size. So, when you use the superviews frame, you are using its initial frame. Which is not correct in most cases.

You have 3 ways to do it correctly:

  • Use autolayout constraints for your newView

  • Set newViews frame in the viewDidLayoutSubviews method. Which is called when the autolayout engine finishes determining the frames actual values. (Note: This method can be called multiple times)

  • Set an autoresizing mask for newView

Try this:

Swift 1 and 2:

newView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

Swift 3+:

newView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

If it doesn't work, also this:

iBag.autoresizesSubviews = true