UIView autoresizing

I could easily spend hours (if not days) trying to figure it out (I’ve already spent several hours at this !!!)

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

enter image description here

At a certain point in time, I add it as a subheading view in a UITableViewCell. I'm calling

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

and when I initialize my subtitle, I:

 [self setAutoresizesSubviews:YES] 

From my graphic it is clear that I assume that only the width changes. What do I need to do to get mySubview's right-hand sub-point to expand to full width while preserving the original origin?

I could easily approach all this in my thoughts, and I welcome any suggestions!

EDIT Thank you very much for your help, Khanh Nguyen

So, as I said, when I initialize v1 (and, by definition, v2), I do not know the size of v1.

When I know the boundaries, I want to host v1, I assume I can do something like this:

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

or C I just install autoresizingMask on v2 as soon as I create it (when I don't know the size of v1 yet)?

+4
source share
1 answer

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

 v2.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin; 

For Swift:

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

By default, autoresizesSubviews is YES. You do not need to install it.

EDIT

Each view has dimensions, even if you don't know it (just do an NSLog if you want to find out). If a view has just been started, its dimensions are likely (0, 0). autoresizesSubviews works even in this case if you know how many intervals you need between subview and superview.

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

 // v1 has been initialized, and its dimensions are unknown (to you) // It 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; 

Pay attention to the third line, v2.frame will be set to some negative numbers, if v1 is zero size initially, but the last one, when v1 frame is set to its correct size (either by you or UITableViewCell ), v2 will resize accordingly (due to limitations of auto-detection) and will become exactly what you want to achieve.

+1
source

Source: https://habr.com/ru/post/1491915/


All Articles