Ipad NavigationBar Landscape Issue

2019-07-24 15:34发布

问题:

is there a way to use a different images for the ipad landscape/portrait mode? My navigationbar contains a logo in the middle and while it works great on the iphone with different images, I can't use different images for the iPad so the logo isn't centered when you turn the device.

Alternatively, I can use a plain background image and maybe replace the navigation bar title with an image or center a button but I also couldn't manage to do that either. (I don't have a UINavigationController subclass).

here is my code that is doing the trick so far inside the app delegate:

if ([UINavigationBar respondsToSelector:@selector(appearance)]) {

        // Create resizable images for iphone
        UIImage *navbarImage44 = [[UIImage imageNamed:@"nav_bar"]
                                  resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];

        UIImage *navbarImage32 = [[UIImage imageNamed:@"nav_bar_landscape"]
                                  resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];

        // Overide for iPad
        // In theory navbar_bg_landscape~iPad should work
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            //use iPad specific image extending last pixel for landscape mode
            [[UINavigationBar appearance] setBackgroundImage:[[UIImage imageNamed:@"nav_bar_ipad" ]
                                 resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)]
                                               forBarMetrics:UIBarMetricsDefault];

        }else {

            // Set the background image for *all* UINavigationBars
            [[UINavigationBar appearance] setBackgroundImage:navbarImage44
                                               forBarMetrics:UIBarMetricsDefault];

            // Never called on iPad, used for landscape on iPhone
            [[UINavigationBar appearance] setBackgroundImage:navbarImage32
                                               forBarMetrics:UIBarMetricsLandscapePhone];
        }



    }

回答1:

I didn't get any response on this so I found a work around which is to resize the image on landscape. I'm ok with that for now. I'm resizing my portrait background image - here is my code for iPad

    // Create resizable images
                UIImage *ipadTabBarBG = [[UIImage imageNamed:@"nav_bar_ipad.png"]
                                            resizableImageWithCapInsets:UIEdgeInsetsMake(0, -260, 0, 0)];

// Set the background image for *all* UINavigationBars
            [[UINavigationBar appearance] setBackgroundImage:ipadTabBarBG
                                               forBarMetrics:UIBarMetricsDefault];