Seifolahi Seifolahi - 4 months ago 17x
Swift Question

How to set UIView size to match parrent without constraints programmatically

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

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.


So many answers and nobody explain whats wrong.

I will try. You setting up frame of your newView by superview frame before the autolayout engine start work to determine views position. So, when you use frame of newView's superview, you use initial frame, that not correct in most cases. You have 3 ways to do right thing: use autolayout (constraints) for your newView, OR set up frames for newView in viewDidLayoutSubviews method (it calls when autolayout engine end it work, so frames become actual; note that this method can be called multiple times), OR setup autoresizing mask for newView