Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set UIView size to match parent without constraints programmatically

Tags:

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.

like image 409
Seifolahi Avatar asked Jun 09 '16 12:06

Seifolahi


People also ask

What is the correct way to set UIView frame?

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.

What is UIView in Swift?

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.


2 Answers

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

like image 73
Vic Avatar answered Sep 18 '22 05:09

Vic


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 is called when the autolayout engine finishes determining the frames actual values. (Note: This method can be called multiple times)

  • Set an autoresizing mask for newView
like image 30
Shadow Of Avatar answered Sep 21 '22 05:09

Shadow Of