Jared Price Jared Price - 1 year ago 138
iOS Question

XCode iPhone how to handle vertical alignment of UI elements

I'm using XCode 5 developing for iOS 7 for an iPhone app. I just started testing on an actual device and right away I noticed the landscape view for every view is not how I want it. Many elements are being hidden.

My view in portrait view:

enter image description here

Ok, that's great, but then this is what it's like in landscape view:

enter image description here

Well that looks awful. So I got everything working how I want horizontally using trailing space to container and leading space to container like so:

enter image description here

Ok, cool. Now the landscape view looks like this:

enter image description here

Ok, I'm getting warmer. Now I can't figure out for the life of me how to set up everything vertically how I want it. Basically I need everything to have an even amount of vertical distance between each UI element starting below the Log Out button and ending at the bottom constraint. How can I do this?


At this point, I'm looking into doing this programmatically. With willRotateToInterfaceOrientation and some simple geometry I think I can figure it out.

Answer Source

I ended up using viewDidLayoutSubviews. Then I used setFrame for each UI element to programmatically set the location of each element.

For others with this issue here is what your code might look like:

    [super viewDidLayoutSubviews];

    CGSize size = [UIScreen mainScreen].bounds.size;
    UIApplication *app = [UIApplication sharedApplication];
    UIInterfaceOrientation orientation = [app statusBarOrientation];

    if (UIInterfaceOrientationIsLandscape(orientation)) size = CGSizeMake(size.height, size.width);
    if (!app.statusBarHidden) size.height -= MIN(app.statusBarFrame.size.width, app.statusBarFrame.size.height);

    if (UIInterfaceOrientationIsLandscape(orientation))
        // code to handle UI elements in landscape view here
        // x and y can be anything from 0 to size.height for y and size.width for x

        // example:

        CGRect logOutFrame = [self logOutButton].frame;
        logOutFrame.origin.y = 10;
        logOutFrame.origin.x = 20;
        logOutFrame.size.width = 80;
        logOutFrame.size.height = 30;            

        [[self logOutButton] setFrame:logOutFrame];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download