除了扩展drawRect外另外一种自定义导航栏背景吗?

查了很多资料,网上的自定义导航栏的方法,清一色的是扩展navigationBar的drawRect方法.然而这样的扩展会影响到工程里所有的navigationBar.或许你并不想这么做,而且很多不合常规的UI用这种方法根本没法实现.

做了无数实验,尝试了各种方法,今天跟大家分享一个新方法:

 

#import <QuartzCore/QuartzCore.h>
    
@interface DDNavigationViewController : UINavigationController<UINavigationControllerDelegate> {
    
     CALayer *_barBackLayer;
    
}
    
@end
@implementation DDNavigationViewController
  
  
  
- (id)initWithRootViewController:(UIViewController *)rootViewController {
  
     self = [super initWithRootViewController:rootViewController];
  
     self.delegate = self;
  
     return self;
  
}
  
- ( void )loadView {
  
     [super loadView];
  
      
  
     UINavigationBar *bar = self.navigationBar;
  
  
  
     CALayer*layer = [CALayer layer];
  
     UIImage *navBarImage = [UIImage imageNamed:@ "navigationBarBackground.png" ];
  
     layer.contents = (id)navBarImage.CGImage;
  
     layer.frame= CGRectMake(0, 0, 320, navBarImage.size.height);
  
     [bar.layer insertSublayer:layer atIndex:0];
  
     _barBackLayer = layer;
  
}
  
  
  
#pragma mark -
  
#pragma mark UINavigationControllerDelegate
  
- ( void )navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:( BOOL )animated {
  
     [_barBackLayer removeFromSuperlayer];
  
     [navigationController.navigationBar.layer insertSublayer:_barBackLayeratIndex:0];
  
}
  
@end

你可能感兴趣的:(除了扩展drawRect外另外一种自定义导航栏背景吗?)