IOS--自定義導(dǎo)航欄漸變顏色


前言

很多APP現(xiàn)在的導(dǎo)航條初始時透明 隨著表頭視圖的上滑逐漸變不透明 下拉表頭視圖時逐漸透明
所以就想做一個小demo分享一下

先看看效果

iosgif.gif

實現(xiàn)

第一步:
創(chuàng)建UINavigationController并且讓他隱藏

UINavigationController * nav=[[UINavigationController alloc] initWithRootViewController:[[ViewController alloc] init]];//創(chuàng)建
nav.navigationBar.hidden=YES;//隱藏

第二步:
創(chuàng)建要用到的宏定義與屬性:

#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width
#define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height

@property(strong,nonatomic)UIView * navView ;  //替換navigationBar
@property(strong,nonatomic)UIImageView * image; //計算表頭圖片的高度要用
@property(assign,nonatomic)CGFloat alp; //透明度

第三步:
自定義uiview視圖覆蓋UINavigationController位置

self.navView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
[self.navigationController.view addSubview:self.navView];
self.automaticallyAdjustsScrollViewInsets=NO; //不要自動掉64高度
UITableView * table=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
[self.view addSubview:table];

第四步:重點來了
調(diào)用 -(void)scrollViewDidScroll:(UIScrollView *)scrollView
方法實現(xiàn)滾動tableView導(dǎo)航的透明度逐漸變化


注意 :這個方法是delegate里的方法,一定要先引代理

 -(void)scrollViewDidScroll:(UIScrollView *)scrollView{
self.alp=scrollView.contentOffset.y/(self.image.bounds.size.height-64);//tableView的偏移量?表頭圖片的高度
self.navView.backgroundColor=[[UIColor orangeColor] colorWithAlphaComponent:self.alp];//透明度逐漸變化

}

結(jié)語:

還有一些簡單的代碼如:創(chuàng)建tableView和實現(xiàn)代理就不貼出來了,避免文章冗長。
github:https://github.com/tmwo/navigationBar_color
還有

與其感慨路難行,不如馬上出發(fā)

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

相關(guān)閱讀更多精彩內(nèi)容

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