UINavigationBar's drawRect is not called in iOS 5.0

后端 未结 7 1893
清歌不尽
清歌不尽 2020-11-28 07:59

I\'ve overrided(placed in category, or swizzled) UINavigationBar\'s drawRect to show custom background. In iOS 5 it\'s not working. What should I do?

7条回答
  •  孤独总比滥情好
    2020-11-28 08:23

    Follow this link to make your code compatible with iOS4, 5 and 6.

    You just have to make in Photoshop or other software a rectangular with the size of 320x44 or 640x88 (for retina display) and import it to your project

    In AppDelegate use this code (in the header between #import and @implementation AppDelegate):

    @implementation UINavigationBar (CustomImage)
    - (void)drawRect:(CGRect)rect {
        UIImage *image = [UIImage imageNamed:@"top_bar.png"];
        [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    }
    @end
    

    In viewDidLoad use this code for iOS5 and iOS6:

    #if defined(__IPHONE_5_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_5_0
        if ([self.navigationController.navigationBar respondsToSelector:@selector( setBackgroundImage:forBarMetrics:)]){
            [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"top_bar.png"] forBarMetrics:UIBarMetricsDefault];
        }
    #endif
    

提交回复
热议问题