導航欄動態(tài)漸變

設置導航欄漸變關鍵亮點第一navigationController.navigationBar.translucent = YES;第二設置navigationController.navigationBar的背景圖片,導航欄的透明度漸變其實就是背景圖透明度的漸變。

Jun-21-2021 11-31-56.gif

我們平時應用時,導航欄漸變同時也會改變狀態(tài)欄顏色和導航欄上文字和圖標的顏色。

關鍵代碼

/**
 注意,要在控制器里設置導航欄狀態(tài)需要先在Info.plist設置View controller-based status bar appearance 為YES,
在有導航欄的頁面,一定要設置導航欄控制器preferredStatusBarStyle由visibleViewController即他的子控制決定(見BaseNavigationController),
然后在子控制起設置preferredStatusBarStyle
 */
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (self.navBarAlpha > 0.8) {
        return UIStatusBarStyleLightContent;
    }
    return UIStatusBarStyleDefault;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offset = scrollView.contentOffset.y;
    CGFloat alpha = offset / 40;
    self.navBarAlpha = alpha;
    NSLog(@"y軸偏移量:%f*******透明度:%f",offset,alpha);
    //這兒imageWithColor方法為自定義color轉(zhuǎn)image
    [self.navigationController.navigationBar setBackgroundImage:[Tools imageWithColor:[UIColor colorWithRed:246/255.0 green:18/255.0 blue:56/255.0 alpha:alpha] size:CGSizeMake(1, 1)] forBarMetrics:UIBarMetricsDefault];
    if (alpha > 0.8) {
        [self setLightStyle];
    } else {
        [self setBlackStyle];
    }
    [self setNeedsStatusBarAppearanceUpdate];//更新狀態(tài)欄
}

- (void)setBlackStyle {
    self.rightBarBtnItem.image = [[UIImage imageNamed:@"buycarblack"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName:[UIFont systemFontOfSize:17]};
    self.navigationController.navigationBar.translucent = YES;
}

- (void)setLightStyle {
    self.rightBarBtnItem.image = [[UIImage imageNamed:@"buycarwhite"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:17]};
    self.navigationController.navigationBar.translucent = NO;//這兒設置為NO是為了保證導航欄一點不透明,視覺不看到下一層
}

特別要注意的是當導航欄背景圖透明度為1.0時,若是不設置navigationController.navigationBar.translucent = NO,這時導航欄其實處于半透明的,看得到下面的圖層,這兒可以根據(jù)實際需要設置,當設置為NO時,一定要記得在viewDidload中設置self.extendedLayoutIncludesOpaqueBars = YES,YES是為了保證設置導航欄translucent為NO時self.view的起點依然為(0, 0),否則會變?yōu)?0,狀態(tài)欄高度+導航欄高度);出現(xiàn)跳動。

具體實現(xiàn)可以下載demo查看

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容