Jacksonkr
Jacksonkr

Reputation: 32247

ios uiview auto-expand dimensions

I have a UIView with the width/height of 0/0. As I add subviews to my UIView, is there a way to make the width and height update automatically?

e.g. if I added 10 subviews side to side that each have a width of 50 then I would expect my UIView to have a width of 500.

Upvotes: 1

Views: 2229

Answers (3)

chih-chun chan
chih-chun chan

Reputation: 146

Yes, UIView can do that. I encountered this issue recently, and here is my solution.

Say you have an UIView and 10 subviews inside it. You must set constraints to the subviews so that the outside UIView would know what size it gonna to be.

For example, you wanna vertically layout the 10 subviews. The constraints would be that

  • The 1st subview has top margin constraint related to the outside UIView
  • The 2nd subview has top margin constraint related to the 1st subview.
  • The 3rd subview has top margin constraint related to the 2nd subview.
  • And so on...
  • The 10th subview has top margin constraint related to the 9th subview.
  • And most importantly, the 10th subview must have bottom margin constraint related to the outside UIView.

To satisfy the constraints above, the outside UIView must have a height that wrap the 4 child subviews automatically.

Upvotes: 0

DBD
DBD

Reputation: 23223

UIView's sizeToFit will resize your view to be big enough to fit all the stuff inside it.

BUT... this is very dependent on the subviews you added to your view. Adding a view is as simple as:

[myView addSubview:innerView];

The frame of the inner makes a big difference.

If you add 10 subviews with x/y origin of 0/0 and width/height of 0/0 then sizeToFit will say you need your view needs a width/height of 0/0 to fit all the subviews.

If you add 1 subview with x/y origin of 10/10 and width/height of 5/5 then sizeToFit with say you need a width/height of 15/15 to fit all the subviews.

Upvotes: 2

Apurv
Apurv

Reputation: 17186

I do not come across any such functionality that will do it automatically. You will have to set frame by calculating the positions and sizes of its sub views.

Upvotes: 1

Related Questions