UIView Autoresizing

Adam picture Adam · Jul 17, 2013 · Viewed 9.3k times · Source

I could easily spend hours (if not days) trying to figure this out (I'm already several hours into it!!!)

I have a UIView that contains subviews (see attached graphic) and is built before it is even added as a subview to anything.

enter image description here

At a certain point in time, I add it as a subview view to a UITableViewCell. I call

[tableViewCell.contentView addSubview:mySubview]
    //....
[mySubview setBounds:tableViewCell.contentView.bounds]

and when I init my subview I have:

[self setAutoresizesSubviews:YES]

From my graphic, you can see I am assuming that only the width changes. What do I have to do to get the right hand subview of mySubview to expand to the full width while maintaining it's original origin?

I could easily be approaching this all wrong in my thinking and I welcome any suggestions!

EDIT Thanks very much for your assistance, Khanh Nguyen

So, as I previously stated, when I init v1, (and, by definition v2) I don't know the dimensions of v1.

When I do know the bounds I want to place v1 in I am assuming I can do something like this:

[v1 setBounds:(some CGRECT)];
v2.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;

or C I just set the autoresizingMask on v2 as soon as I instantiate it (when I still don't know the dimensions of v1)?

Answer

Khanh Nguyen picture Khanh Nguyen · Jul 17, 2013

If you have a view v1, its subview v2 and you want v2 to have fixed left edge, while its width changes when v1 is resized (i.e. distance between v1's right edge and v2's right edge is constant), use this:

v2.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;

For Swift:

v2.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleBottomMargin]

By default, autoresizesSubviews is YES. You don't need to set it.

EDIT

Every view has dimensions, even if you don't know it (just do an NSLog if you want to know it). If the view has just been init'ed, its dimensions are likely (0, 0). autoresizesSubviews works even in that case, as long as you know how much spacing you need between the subview and the superview.

For example, you want v2 is 10px from v1 for left margin and 20px for right margin, the following will do

// v1 has been initialized, and its dimensions are unknown (to you)
// It's probably (0, 0), but that doesn't matter
// 30px = 10px + 20px
v2.frame = CGRectMake(10, 0, v1.bounds.size.width - 30, 100);
v2.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;

Note the third line, v2.frame will be set to some negative numbers if v1 has zero size initially, but latter when v1's frame is set to its proper size (either by you or UITableViewCell), v2 will resize accordingly (because of the autoresizing constraint) and become exactly what you want to achieve.