How to set UIView size to match parent without constraints programmatically How to set UIView size to match parent without constraints programmatically ios ios

How to set UIView size to match parent without constraints programmatically


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


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 iscalled 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

subview.frame = parentView.bounds

subview.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

parentView.addSubview(subview)