Custom background image on UIToolbar in IOS5 SDK

試著忘記壹切 提交于 2019-11-28 16:43:14
Simone

You can use: [[UIToolBar appearance] setBackgroundImage:toolBarIMG forBarMetrics:UIBarMetricsDefault]; (new in iOS 5)

loretoparisi

Suppose you linked iOS5 beta SDK, you could do something like this

if([navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        //iOS 5 new UINavigationBar custom background
        [navigationBar setBackgroundImage:image forBarMetrics: UIBarMetricsDefault];
} 

To realize this, take a look at here iOS 4.3 to iOS 5.0 API Differences and search for "UINavigationBar.h"

or take a close look at the new method signature here setBackgroundImage:forBarMetrics:

Also here is the UIBarMetrics enum type

Hope this helps.

This worked on my toolbar:

//toolBar background image set based on iOS version
    [[UIDevice currentDevice] systemVersion];

    if ([[[UIDevice currentDevice] systemVersion] floatValue] > 4.9) {

        //iOS 5
        UIImage *toolBarIMG = [UIImage imageNamed: @"toolBar_brown.png"];  

        if ([toolBar respondsToSelector:@selector(setBackgroundImage:forToolbarPosition:barMetrics:)]) { 
            [toolBar setBackgroundImage:toolBarIMG forToolbarPosition:0 barMetrics:0]; 
        }

    } else {

        //iOS 4
        [toolBar insertSubview:[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"toolBar_brown.png"]] autorelease] atIndex:0]; 

    }

This method is not documented and relies on specific subviews structure of UIToolbar which can be changed from version to version. So that exactly what probably happened with iOS5 release

P.S. If you check updated UIToolBar class reference you'll find another way to customize UIToolBar

This is along the same line as Simone's answer, but works for iOS 5 and iOS < 5. This is what I'm using in app. You need to call [UINavigationBar setupIos5PlusNavBarImage] somewhere in your app initialization (applicationDidFinishLaunching: is a good candidate). On iOS 5+, setupIos5PlusNavBarImage will use the new UIAppearance protocol to set the background and the drawRect override will be ignored. On iOS < 5, setupIos5PlusNavBarImage will basically be a no-op and the drawRect will handle drawing the image.

Interface:

@interface UINavigationBar (CustomNavigationBar)

+ (void) setupIos5PlusNavBarImage;

- (void) drawRect: (CGRect) rect;

@end

Implementation:

@implementation UINavigationBar (CustomNavigationBar)

+ (void) setupIos5PlusNavBarImage
{
    if ([UINavigationBar respondsToSelector: @selector(appearance)])
    {
        [[UINavigationBar appearance] setBackgroundImage: [UIImage imageNamed: @"menuBar.png"] forBarMetrics: UIBarMetricsDefault];
    }
}

- (void) drawRect: (CGRect) rect
{
    UIImage* img = [UIImage imageNamed: @"menuBar.png"];
    [img drawInRect: CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}

@end
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!