考虑到继承UINavigationBar使用起来会非常不便,我们决定用Category来实现,首先定义我们的category:
@interface UINavigationBar (BackgroundColor) - (void)lt_setBackgroundColor:(UIColor *)backgroundColor;@end
实现:我们使用associatedObject将overlayView动态地绑定到UINavigationBar的instance上,当调用lt_setBackgroundColor的时候,我们只要更新这个overlayView就行啦~
@implementation UINavigationBar (BackgroundColor)static char overlayKey; - (UIView *)overlay { return objc_getAssociatedObject(self, &overlayKey); } - (void)setOverlay:(UIView *)overlay { objc_setAssociatedObject(self, &overlayKey, overlay, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (void)lt_setBackgroundColor:(UIColor *)backgroundColor { if (!self.overlay) { [self setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault]; // insert an overlay into the view hierarchy self.overlay = [[UIView alloc] initWithFrame:CGRectMake(0, -20, [UIScreen mainScreen].bounds.size.width, self.bounds.size.height + 20)]; self.overlay.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; [self insertSubview:self.overlay atIndex:0]; } self.overlay.backgroundColor = backgroundColor; } @end
最后在scrollViewDidScroll中,我们就可以动态地修改UINavigationBar的backgroundColor了:
[self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:alpha]];
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
CGFloat alpha=scrollView.contentOffset.y/90.0f>1.0f?1:scrollView.contentOffset.y/90.0f;
[self.navigationController.navigationBar setBackgroundImage:[self getImageWithAlpha:alpha] forBarMetrics:UIBarMetricsDefault];
}
#pragma handle image -mark
//合成图片
-(UIImage *)getImageWithAlpha:(CGFloat)alpha{
UIColor *color=[UIColor colorWithRed:1 green:0 blue:0 alpha:alpha];
CGSize colorSize=CGSizeMake(1, 1);
UIGraphicsBeginImageContext(colorSize);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
UIImage *img=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}