How does autoresizing mask work?

J Max picture J Max · Dec 5, 2011 · Viewed 8k times · Source

I've found a lot of information on autoresizing but none has been able to solve my problem. I have a ViewController (RAViewController) who calls a view in its loadView method like so:

- (void)loadView
{
    // Set Navigation Bar Title
    self.navigationItem.title = @"RA";

    // Add Background view
    self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    // Add RAView
    RAView *rAView = [[RAView alloc] initWithFrame:self.view.frame Controller:self];
    [self.view rAView];
}

The view it calls (RAView) looks like this:

- (id)initWithFrame:(CGRect)frame Controller:(RAViewController *)Controller
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.autoresizesSubviews = YES;
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.backgroundColor = [[UIColor alloc] initWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];

        controller = Controller;

        // Draw Architecture View
        [self drawArchitectureView];
    }
return self;
}

-(void)drawArchitectureView {
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, self.frame.size.width - 20, 50);

    [button setBackgroundColor:[UIColor grayColor]];
    [button setTitle:@"Overview" forState:UIControlStateNormal];

    [self addSubview:button];
}

For some reason I can't get autoresizing mask to resize the button width when the device is landscape. Any help is greatly appreciated.

Answer

Darek Rossman picture Darek Rossman · Dec 5, 2011

If you want it to keep the same height, but just stay fully centered, 10.0 from the left and right, try:

-(void)drawArchitectureView {
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, self.frame.size.width - 20, 50);

    button.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;

    [button setBackgroundColor:[UIColor grayColor]];
    [button setTitle:@"Overview" forState:UIControlStateNormal];

    [self addSubview:button];
}