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.
1) Control-drag from a frame view (e.g. questionFrame) to main View, in the pop-up select "Equal heights". 2)Then go to size inspector of the frame, click edit "Equal height to Superview" constraint, set the multiplier to 0.7 and hit return.
The UIView class is a concrete class that you can instantiate and use to display a fixed background color. You can also subclass it to draw more sophisticated content.
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 newView
s 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)
newView
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With