UINavigationBar's drawRect is not called in iOS 5.0

后端 未结 7 1873
清歌不尽
清歌不尽 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条回答
  •  Happy的楠姐
    2020-11-28 08:22

    Setting custom background for UINavigationBar to support iOS5 and iOS4 too!

    http://www.mladjanantic.com/setting-custom-background-for-uinavigationbar-what-will-work-on-ios5-and-ios4-too/

    http://rogchap.com/2011/06/21/custom-navigation-bar-background-and-custom-buttons/


    As you know, until iOS 5 came out, we used drawRect override in AppDelegate to customize UINavigationBar. But know, iOS 5 give us some new method for styling (and old doesn’t work).

    How to build app that will work on iOS 4 and iOS 5 with stylized UINavigationBar?

    You must to do both!

    In AppDelegate use this code:

    @implementation UINavigationBar (UINavigationBarCategory)
    - (void)drawRect:(CGRect)rect {
    UIImage *img = [UIImage imageNamed:@"navbar.png"];
    [img drawInRect:rect];
    }
    @end
    

    and in viewDidLoad method for iOS5 (in your view implementation):

    if ([self.navigationController.navigationBar respondsToSelector:@selector( setBackgroundImage:forBarMetrics:)]){
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbar.png"] forBarMetrics:UIBarMetricsDefault];
    }
    

    If you see, here we are asking if navbar will respondToSelector to avoid crash on iOS4!

提交回复
热议问题