很多時候 項(xiàng)目中要求導(dǎo)航欄的顏色隨著scrollview的滾動發(fā)生漸變,于是自己就寫了一個demo沒方法比較簡單 寫一個UINavigationBar的分類 在分類的.h文件中聲明兩個方法?
#import@interface UINavigationBar (LH)
- (void)lhSetBackgroundColor:(UIColor *)backgroundColor;
- (void)lhReset;
@end
在.m文件中實(shí)現(xiàn)方法 其中需要注意的是 用到了runtime的關(guān)聯(lián)對象 ,關(guān)聯(lián)對象就是把兩個對象相互關(guān)聯(lián)起來,使得一個對象多為另一個對象的一部分.具體講解以后會給大家以文章形式寫出來 ,這里就不過多講解了
#import@implementation UINavigationBar (LH)
static char overlayKey;
- (UIView *)overlay{
return objc_getAssociatedObject(self, &overlayKey);
}
- (void)setOverlay:(UIView *)overlay{
objc_setAssociatedObject(self, &overlayKey, overlay, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)lhSetBackgroundColor:(UIColor *)backgroundColor{
if (!self.overlay) {
[self setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
self.overlay? = [[UIView alloc] initWithFrame:CGRectMake(0, -20, [UIScreen mainScreen].bounds.size.width, CGRectGetHeight(self.bounds)+20)];
self.overlay.userInteractionEnabled = NO;
self.overlay.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[self insertSubview:self.overlay atIndex:0];
}
self.overlay.backgroundColor = backgroundColor;
}
- (void)lhReset{
[self setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
[self.overlay removeFromSuperview];
self.overlay = nil;
}
@end
現(xiàn)在是只要在你要實(shí)現(xiàn)的控制器中調(diào)用這連個方法就好了 其中最主要的方法就是
#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
UIColor *color = [UIColor colorWithRed:45/255.0 green:45/255.0 blue:45/255.0 alpha:1];
CGFloat offsetY = scrollView.contentOffset.y;
if (offsetY >= - self.view.frame.size.height ) {
CGFloat alpha = 1- offsetY/self.view.frame.size.height;
[self.navigationController.navigationBar lhSetBackgroundColor:[color colorWithAlphaComponent:alpha]];
self.titlelabel.alpha = alpha;
} else {
[self.navigationController.navigationBar lhSetBackgroundColor:[color colorWithAlphaComponent:0]];
}
}
當(dāng)然不會忘了demo的連接的:https://git.oschina.net/huanni/scrollviewNav.git
效果圖如下