記錄一下今天遇見的一個小需求!
需要做一個滾動導航欄漸變 紫色滾動白色 在白色變回紫色!
feiHua不多說!直接上代碼
首先我封裝了一個View ?在這個View里面寫一個代理 因為我的需求導航欄上面的按鈕是可以點擊操作的!然后在自定義一個方法用于變色!
.h文件
#import
@protocolNavigationViewDelegate
@optional
- (void)navigationViewClicked:(UIButton*)btn;
@end
@interfaceNavigationView :UIView
@property (nonatomic, assign) id<NavigationViewDelegate>delegate;
@property(nonatomic, strong) UIButton *messageButton;
@property(nonatomic, strong) UIButton *storeButton;
- (void)scrollColorChangeNavigationWithOffset:(CGPoint)Offset;
@end
.m文件核心代碼
#pragma mark - 漸變nav
- (void)scrollColorChangeNavigationWithOffset:(CGPoint)Offset
{
? ? NSLog(@"======+++++%f",Offset.y);
? ? CAGradientLayer *gradient = [CAGradientLayer layer];
? ? gradient.hidden=YES;
? ? //動態(tài)獲取手機導航欄高度
? ? CGFloat ?statusHeight =kStatusHeight+44;
? ? CGFloat ?alpha = ((statusHeight-(Offset.y<= statusHeight ? Offset.y: statusHeight))/statusHeight);
NSLog(@"_______%f",alpha);
?? ?self.backgroundColor = [[UIColor colorWithRed:130/255.0 green:3/255.0 blue:124/255.0 alpha:1]colorWithAlphaComponent:alpha];
}
在你需要變色的控制器遵循試圖滾動的代理方法
#pragma mark -- 懶加載
// 創(chuàng)建Navigation
- (NavigationView*)navigationView
{
? ? if (!_navigationView)
? ? {
? ? ? ? self.navigationView = [[NavigationView alloc]initWithFrame:CGRectMake(0,0,WIDTH,kStatusHeight+44)];
? ? ? ? UIColor *color = [UIColor? colorWithRed:126/255.0 green:100/255.0 blue:30/255.0 alpha:1];
? ? ? ? _navigationView.backgroundColor = [color colorWithAlphaComponent:1];
? ? ? ? _navigationView.delegate = self;
? ? ? ? [self.navigationController.view addSubview:_navigationView];
? ? }
? ? return _navigationView;
}
#pragma mark - 導航欄漸變
- (void)scrollViewDidScroll:(UIScrollView*)scrollView
{
?? ?scrollViewContentOffset = scrollView.contentOffset.y;
? ? //改變Nav顏色&圖標顏色
? ? [self.navigationView scrollColorChangeNavigationWithOffset:scrollView.contentOffset];
}
如果別的控制器不需要變色 在頁面即將出現(xiàn)的時候添加navigationView 即將消失的時候刪除就行了! ?(菜鳥指導,大神勿噴!)
----------------------------夢想是工程師的少年---------------------------
最后感謝你的觀看!有什么不足 請指導!