Search code examples
ios5uiviewautoresizingmask

UIView horizontal centering using autoresizingmask not working


I am having problems in centering a UIView in the middle of detail view in master-detail application template in iOS5. The view is of width less than the iPad screen and it should always appear in center irrespective of the device orientation. Here's what I tried....

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.view setAutoresizingMask:(UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin)];
    [self.view.layer setBorderWidth:2.0F];
    [self.view.layer setBorderColor:[[UIColor orangeColor] CGColor]];

    // Do any additional setup after loading the view, typically from a nib.
    UIView *someContainerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 600.0F, 56.0F)];
    [someContainerView.layer setBorderWidth:2.0F];
    [someContainerView.layer setBorderColor:[[UIColor greenColor] CGColor]];
    [someContainerView setAutoresizingMask:(UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin)];
    [self.view addSubview:someContainerView];

    [self configureView];
}

Here's how the view appears

enter image description here

Can somebody tell me what I am missing over here????


Solution

  • Okay here's what I solved this problem. When creating the UIView, I changed this

    CGRectMake((0, 0, 660.0f, 56.0F)];
    

    to this...

    CGRectMake((self.view.bounds.size.width-660.0F)/2, 0, 660.0f, 56.0F)];
    

    Since I am using autoresizingmask with flexible left/right margin, hence I actually need to position the UIView in center for the autoresizing to work its magic by maintaining the left/right margins when the view rotates.