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.
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)
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.
may be this will work:-
but in your case,
width
andheight
inside the CGRect should beand then add to it's parent as subview.
Try this,
or you can use
viewWillAppear
orviewDidAppear
to set frame.Because in
viewDidload
your iBag's frame is same which is in your interface builder (storyboard). Now it will change according to your constraints and device size on which you run. So, inviewDidload
your new view get old frame not changed frame. So, it's better to useviewDidLayoutSubviews
orviewWilAppear
.Second thing, Either use autolayout everywhere or nowhere. It is bad practice to use autolayout in parent view and not to child.
Try this
subview.frame = parentView.bounds
subview.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
parentView.addSubview(subview)