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.