Question

I have a strange problem which probably has a very simple solution, I just can't see it ...

I have an UIView class which contains a button as a subview, spanning the 4/5th of the width and one third of the view's height. When the parent view is resized (eg have the height and half the width), the button should stay where it is (top third of the parent view), and now also have half the width and still one third of the new height.

That means:

Parent before: Frame (0,0,100,100)
Button before: Frame (0,0,80,33.3)

Parent after: Frame (0,0,50,50)
Button after: Frame (0,0,40,16.7)

Problem is, button after always has the Frame (0,0,30,0). It seems as if the new width and height of the button i just achieved by subtracting the 50 pixel change, instead of doing a proportional resize. Must be something really stupid, but I just can't find it.

Here is the code of my UIView class:

-(id)init
{
    self = [super init];
    if(self)
    {
        self.autoresizesSubviews = true;

        self.frame = CGRectMake(0,0,100,100);
        button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0,0,80, self.frame.size.height / 3);
        button.autoresizingMask = UIViewAutoresizingFlexibleHeight
                                  |UIViewAutoresizingFlexibleWidth;

        [self addSubview:button];
    }

    return self;
}

Anyone an idea? I already tried quite some variations on the autoresizeMask flags, but no avail - and the above flags should also be the right ones ...

Was it helpful?

Solution

This is what you need to do:

button.autoresizingMask = UIViewAutoresizingFlexibleHeight |
                          UIViewAutoresizingFlexibleWidth |
                          UIViewAutoresizingFlexibleRightMargin |
                          UIViewAutoresizingFlexibleBottomMargin;

If you set flexible height and width without setting flexible margins, what happens when you resize is that the height and width change so that the margins (i.e., the distance to the superview's bounds) stays constant.

Setting the height and bottom margin to be flexible makes the top margin stay the same, and the view will resize in proportion to the superview. Same goes for width and right margin.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top