可以任意定製導航欄背景的一個思路
在實際開發中經常遇到設計師給的視覺稿:有些頁面導航欄背景是透明的,有些頁面則是常規導航欄。
由於導航欄是所有子頁面共用的,一旦其中某個頁面單獨設定了導航欄背景,就需要負責儲存之前的狀態,在消失的時候恢復原來的狀態。
系統提供如下方法來設定完全透明的導航欄背景
UIImage *clearImage = [UIImage imageWithColor:[UIColor clearColor]]; [[UINavigationBar appearance] setBackgroundImage:clearImage forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault]; [UINavigationBar appearance].shadowImage = clearImage;
如果使用上面的方法來滿足視覺稿的效果,需要解決兩個問題:
- 每個頁面需要頻繁地儲存和恢復狀態
- 在頁面之間切換時需要保證導航欄的過渡效果自然
那麼,網路上做的比較好的APP,它們是採用了什麼方式來解決這兩個問題的呢?
微博
微博的個人主頁頁面導航欄是透明的,使用之前介紹的方法設定之後的就是這效果。



微信
微信的收付款頁面導航欄是透明的,使用之前介紹的方法設定之後的就是這效果。



總結得出思路
微博和微信的思路都是把導航欄的背景設定控制在當前的頁面中,這樣在頁面切換時就不會受到影響,同時也解決了開頭提到的問題。 如果要在現有專案中進行全域性調整,借鑑上面分析得出的思路,一個比較好的方案就是:
- 把導航欄全域性設定為透明(在 BaseNavigationController 中設定)
- 每個頁面都要有一個「假的」導航欄(在 BaseViewController 中設定)
- 基類(BaseViewController)提供設定「假導航欄」背景的方法
有了可行的思路,程式碼就很簡單了,我已經把以上思路實踐到公司的專案中進行改造,實際效果挺不錯。
