首先定义Category
@interface UINavigationBar (BackgroundColor)
- (void)setAlphaBackgroundColor:(UIColor *)color;
@end
#import "UINavigationBar+Alpha.h"
#import
static void *overlayKey = nil;
@implementation UINavigationBar (BackgroundColor)
- (UIView *)overlay {
return objc_getAssociatedObject(self, overlayKey);
}
- (void)setOverlay:(UIView *)overlay {
objc_setAssociatedObject(self, overlayKey, overlay, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)setAlphaBackgroundColor:(UIColor *)backgroundColor {
if (!self.overlay) {
[self setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
[self setShadowImage:[UIImage new]]; // insert an overlay into the view hierarchy
self.overlay = [[UIView alloc] initWithFrame:CGRectMake(0, -20, [UIScreen mainScreen].bounds.size.width, 64)];
[self insertSubview:self.overlay atIndex:0];
}
self.overlay.backgroundColor = backgroundColor;
}
@end
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
UIColor *color = [UIColor blueColor];
CGFloat offsetY = scrollView.contentOffset.y;
if (offsetY > 0) {
CGFloat alpha = 1 - ((64 - offsetY) / 64);
NSLog(@"alpha:%f", alpha);
[self.navigationController.navigationBar setAlphaBackgroundColor:[color colorWithAlphaComponent:alpha]];
}
else {
[self.navigationController.navigationBar setAlphaBackgroundColor:[color colorWithAlphaComponent:0]];
}
}