Search code examples
iosios5uiviewcgrectcgrectmake

Handling view resizing programatically heights, widths and margins


I am trying to setup a view programatically. Through preference I prefer to programme the views as opposed to using Interface Builder, I feel I have a better control for some reason...

I am setting up a view with two subviews and a button. What I am trying to acheive is the same view when the orientation changes. Initially I thought I needed to calculate the screen size then calculate some divisions to work out the changes, but it appears I can handle on UIViewAutoresizing***

The issue I experience is with the top margin. Here is my code for the subviews.

    // Create sub view for Logo
UIView *logoView =[[UIView alloc] initWithFrame:CGRectMake(0,0,320,280)];
[logoView setBackgroundColor:[UIColor blueColor]];
logoView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;

// Create sub view
UIView *buttonView =[[UIView alloc] initWithFrame:CGRectMake(0, logoView.bounds.size.height, 320,200)];
[buttonView setBackgroundColor:[UIColor redColor]];
buttonView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleTopMargin;

Here is a picture of portrait and landscape where you can see the issue, with the 'white' space.

Portrait

Landscape


Solution

  • You either want the two views (red and blue) to end up with a proportionate amount of space after the rotation:

    logoView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleBottomMargin;
    buttonView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleTopMargin;
    

    Or you want the red view to end up the same size as it started out, and the blue view to adjust to make room for it:

    logoView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    buttonView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleTopMargin;