NavigationBar 渐隐效果
2019獨角獸企業重金招聘Python工程師標準>>>
考慮到繼承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?hierarchyself.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;
}
轉載于:https://my.oschina.net/gongxiao/blog/537848
總結
以上是生活随笔為你收集整理的NavigationBar 渐隐效果的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Swift 数组、字典
- 下一篇: [数据结构]合并有序数组