scrollView滚动导航条渐变

很多时候 项目中要求导航栏的颜色随着scrollview的滚动发生渐变,于是自己就写了一个demo没方法比较简单 写一个UINavigationBar的分类 在分类的.h文件中声明两个方法 

#import@interface UINavigationBar (LH)

- (void)lhSetBackgroundColor:(UIColor *)backgroundColor;

- (void)lhReset;

@end

在.m文件中实现方法 其中需要注意的是 用到了runtime的关联对象 ,关联对象就是把两个对象相互关联起来,使得一个对象多为另一个对象的一部分.具体讲解以后会给大家以文章形式写出来 ,这里就不过多讲解了

#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

现在是只要在你要实现的控制器中调用这连个方法就好了 其中最主要的方法就是

#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]];

}

}

当然不会忘了demo的连接的:https://git.oschina.net/huanni/scrollviewNav.git

效果图如下


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 思路 在UISrollView的delegate方法 - (void)scrollViewDidScroll:(U...
    liu_bo阅读 527评论 0 1
  • 1.QQ动态界面隐藏了navigation bar 和statusbar 隐藏导航条和状态栏 2.附上代码 // ...
    奇怪的知识增加了阅读 726评论 0 1
  • *7月8日上午 N:Block :跟一个函数块差不多,会对里面所有的内容的引用计数+1,想要解决就用__block...
    炙冰阅读 2,532评论 1 14
  • 很早的时候,总是想写些东西,关于别人的,关于自己的,提笔却一点也写不出来。总觉得别人写的不好,缺乏打动人心的东西...
    杨丁阅读 350评论 0 0
  • 尼特赶到牧神街的时候,已经过了夜半。这个夜晚,他喝了一点新酿的苹果酒,又在斯潘徳的神像前祈祷过,丢了几粒神香在铜盘...
    道天生阅读 305评论 0 1