How to set UIView size to match parent without constraints programmatically

Seifolahi picture Seifolahi · Jun 9, 2016 · Viewed 30.5k times · Source

The problem sounds easy but it is making me crazy. I've created a white view in IB that's called iBag and by constraints it's size depends on screen size.

enter image description here

Now I want create a new UIView programmatically and add as subview to iBag with same size and position by this code

let newView = UIView()
newView.frame =  (frame: CGRect(x: 0, y: 0, width: iBag.frame.width, height: iBag.frame.height))
newView.backgroundColor = UIColor.redColor()
iBag.addSubview(newView)

enter image description here

I also tried bounds but that didn't help. I can use constraints to solve the problem but i want to understand what's wrong.

Answer

Vic picture Vic · Jun 9, 2016

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