简体   繁体   中英

How to make a subview automatically resize with its superview?

I have a view which contains one sub-view; this sub-view itself contains another sub-view, which is meant to be slightly smaller than its superview.

I am creating the first subview full-screen size then shrinking it to a very small size on the screen. When the subview is tapped, I animate it from its small size to full-screen.

The problem is that my second subview never resizes itself during this animation - it is always rendered full-size and overflows the bounds of its superview.

Is there a simple way to get a subview to keep itself sized proportionally as its superview changes size?

you could add the autoresizing-behavior programmatically

Objective-C

subview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

Swift 3.x

subview.autoresizingMask = [.flexibleWidth, .flexibleHeight]

Swift 2.x

subview.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

In Interface-Builder navigate to tab 3 and click on the arrows in the middle ;D

Another workaround could be to implement the setFrame-method and always adapt it to the size of the superview (not the given frame.size). Don't forget to set up the origin as you need it.

- (void) setFrame:(CGRect)frame
{
    CGRect rect = self.superview.frame;
    rect.origin.x = 0;
    rect.origin.y = 0;
    [super setFrame:rect];
}

这对我有用

subview.frame = subview.superview.bounds;

If you're using only [.flexibleWidth, .flexibleHeight] for your autoresizing mask, your subview will not get resized proportionally. The right answer is:

autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleLeftMargin, .flexibleBottomMargin, .flexibleRightMargin]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM