Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a subview automatically resize with its superview?

Tags:

iphone

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?

like image 304
MusiGenesis Avatar asked Mar 29 '11 13:03

MusiGenesis


3 Answers

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];
}
like image 156
Lepidopteron Avatar answered Nov 05 '22 06:11

Lepidopteron


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]
like image 29
andrei Avatar answered Nov 05 '22 05:11

andrei


this does the trick for me

subview.frame = subview.superview.bounds;
like image 8
Juraj Petrik Avatar answered Nov 05 '22 05:11

Juraj Petrik