-->

How does autoresizing mask work?

2019-06-20 13:58发布

问题:

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.

回答1:

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];
}