「往上滑,導航欄顏色漸漸浮現」是現在很常見的視覺效果。核心只有一個概念:把 contentOffset 映射成透明度。
- (void)viewDidLoad {
[super viewDidLoad];
[self initTableView];
}
- (void)initTableView {
self.myTableView.delegate = self;
self.myTableView.dataSource = self;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
return [[UITableViewCell alloc] init];
}
UITableView 是 UIScrollView 的子類別,因此只要實作 scrollViewDidScroll: 就能拿到滾動資訊。
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat offset = scrollView.contentOffset.y;
UIColor *color = [UIColor redColor];
if (offset < 0) {
// 下拉過頭時維持全透明
self.navigationController.navigationBar.backgroundColor =
[color colorWithAlphaComponent:0];
} else {
// 64 為導航欄高度,offset 越大透明度越高
CGFloat alpha = 1 - ((64 - offset) / 64);
self.navigationController.navigationBar.backgroundColor =
[color colorWithAlphaComponent:alpha];
}
}
這段公式的運作是:offset 為 0 時 alpha = 0(完全透明),offset 達到 64 時 alpha = 1(完全顯色)。中間的過程因為 scrollViewDidScroll 會以極高頻率觸發,看起來就是連續的漸變。
這裡有幾個實務上會踩到的細節值得留意。
第一,64 這個數字最好別寫死。狀態列 20pt 加上導航欄 44pt 是舊尺寸的假設,在 iPhone X 之後的機型上狀態列高度不同,寫死會導致漸變在錯誤的位置完成。建議改成動態計算 navigationBar.bounds.size.height 加上狀態列高度。
第二,直接改 navigationBar 的 backgroundColor 在 iOS 15 之後可能無效。系統改為使用 scrollEdgeAppearance 與 standardAppearance,若沒設定這兩個屬性,navigationBar 的底色會由系統接管。可行作法是建立一個 UINavigationBarAppearance 物件,設定其 backgroundColor,再同時指定給這兩個屬性,然後在 scrollViewDidScroll 中調整 appearance.backgroundColor 的 alpha。
第三,用 backgroundColor 做漸變會失去半透明模糊效果。若設計稿要求「毛玻璃逐漸加深」,正確做法是調整 barStyle 或使用 visualEffectView,並搭配 changing alpha 的 UIVisualEffectView 遮罩,而非單純改底色。
最後提醒,若在 scrollViewDidScroll 中同時有其他邏輯(例如無限滾動判斷),記得把導航欄這段抽成獨立方法呼叫,避免職責混在一起難以維護。