[iOS]一种可以让UINavigationBar在自定义背景和系统背景切换的办法

关于修改UINavigationBar的背景的介绍网上随处都能看到,其中最好用的就是以下用Category实现方式:

@implementation UINavigationBar (UINavigationBarBackground)

- (void)drawRect:(CGRect)rect 

{

    UIImage *image = [UIImageimageNamed:@"myNaviBG.png"];  

    [image drawInRect:CGRectMake(0,0,self.frame.size.width,self.frame.size.height)];    

}  

@end


但是这种方法存在一个问题,当我们打开其他任何iOS提供的标准控件,如

UIImagePickerController的时候,这上面的NavigationBar也会被改变。当然我们可以通过设置标记重新贴图,但是这样仍然不能用系统提供的NavigationBar的背景,因为这个Category的drawRect已经覆盖了原来的函数。这里提供一种绝对原创方案可以绕过这个问题:

static  IMP originalMethodOfdrawRect;

@implementation UINavigationBar (UINavigationBarBackground)

// 自定义背景颜色

- (void)customizedDrawRect:(CGRect)rect 

{

    UIImage *image = [UIImageimageNamed:@"myNaviBG.png"];  

    [image drawInRect:CGRectMake(0,0,self.frame.size.width,self.frame.size.height)];    

}  


// UIViewController可以通过[self.navigationController.navigationBar setCustomizedNaviBar:YES];

-(void)setCustomizedNaviBar:(BOOL)customized

{

    if (originalMethodOfdrawRect ==nil

    {

      // 记下原始的drawRect:的地址

       originalMethodOfdrawRect = [self methodForSelector:@selector(drawRect:)];

    }

    if (customized) 

    {

       // 当需要自定背景时,替换selector drawRect:的地址。

        class_replaceMethod([self class],@selector(drawRect:), [self methodForSelector:@selector(customizedDrawRect:)],nil);

    }

    else

    {

      //当需要用系统的Navi风格时,把selector的函数地址还原。

        class_replaceMethod([self class],@selector(drawRect:),originalMethodOfdrawRect,nil);        

    }

}

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值