1. 程式人生 > >漸變導航欄終極版

漸變導航欄終極版

以上是博主寫的漸變導航欄的進化之路,上一篇部落格最後說明了升級版中的bug,在這一版中對這一bug進行了修復,其實很簡單,就是增加了一個新的變數來給一個全域性的透明度,在上下滾動時改變這個全域性的透明度,然後判斷透明度的邊界,下面來看看程式碼吧:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor=[UIColor whiteColor];

    lhAlpha = 1
; } - (void)scrollViewDidScroll:(UIScrollView *)scrollView{ currentPostion = scrollView.contentOffset.y; if (currentPostion > 0) { if (currentPostion - _lastPosition >= 0) { if ([[NSUserDefaults standardUserDefaults]objectForKey:@"first"]!=nil) { [[NSUserDefaults
standardUserDefaults]removeObjectForKey:@"first"]; [[NSUserDefaults standardUserDefaults]synchronize]; // [NSObject cancelPreviousPerformRequestsWithTarget:self]; // [self performSelector:@selector(scrollViewDidEndScrollingAnimation:) withObject:nil afterDelay:0.00001];
[[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"second"]; [[NSUserDefaults standardUserDefaults]synchronize]; stopPosition = currentPostion + 64; } _lastPosition = currentPostion; NSLog(@"ScrollUp now current:%f last:%f stop:%f",currentPostion,_lastPosition,stopPosition); if (lhAlpha >= 0) { lhAlpha = lhAlpha - 0.025f; } else { lhAlpha = 0; } self.navigationController.navigationBar.alpha = lhAlpha; // self.navigationController.navigationBar.alpha = 1 - currentPostion / 400; } else { if ([[NSUserDefaults standardUserDefaults]objectForKey:@"second"]!=nil) { [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"second"]; [[NSUserDefaults standardUserDefaults]synchronize]; // [NSObject cancelPreviousPerformRequestsWithTarget:self]; // [self performSelector:@selector(scrollViewDidEndScrollingAnimation:) withObject:nil afterDelay:0.00001]; [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"first"]; [[NSUserDefaults standardUserDefaults]synchronize]; stopPosition = currentPostion + 64; } _lastPosition = currentPostion; NSLog(@"ScrollDown now current:%f last:%f stop:%f",currentPostion,_lastPosition,stopPosition); if (lhAlpha <= 1) { //這裡的0.025自己可以調整,有的上下滾動透明度變化一個快一個慢,切記不要讓向下的小於向上的,否則滾動到頂端導航欄是透明的 lhAlpha = lhAlpha + 0.025f; } else { lhAlpha = 1; } self.navigationController.navigationBar.alpha = lhAlpha; // self.navigationController.navigationBar.alpha = (stopPosition - currentPostion)/200; } } }

Demo的下載地址:下載地址

建議先看一下前面兩篇,這樣會增加理解,實現不難,主要是一個思路。