在許多 App 中,當使用者向下捲動內容時,會希望上方導覽列與下方標籤列自動收起,讓內容顯示區域變大;反之,當使用者向上捲動時,再將它們恢復顯示。
實作重點是監聽 scrollViewDidScroll,取得目前的 contentOffset.y,再判斷使用者是往下捲動還是往上捲動。接著透過 UIView 動畫調整 navigationBar 與 tabBar 的 frame。
以下概念程式碼展示如何依捲動方向收合與恢復:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat offsetY = scrollView.contentOffset.y;
if (offsetY > 0) {
[UIView animateWithDuration:0.25 animations:^{
self.navigationController.navigationBar.frame = CGRectMake(0, -44, self.view.bounds.size.width, 44);
self.tabBarController.tabBar.frame = CGRectMake(0, self.view.bounds.size.height, self.view.bounds.size.width, 49);
}];
} else {
[UIView animateWithDuration:0.25 animations:^{
self.navigationController.navigationBar.frame = CGRectMake(0, 0, self.view.bounds.size.width, 44);
self.tabBarController.tabBar.frame = CGRectMake(0, self.view.bounds.size.height - 49, self.view.bounds.size.width, 49);
}];
}
}
實際專案中,建議再加上狀態判斷,例如只在特定頁面啟用、避免動畫重複觸發,或根據安全區域與螢幕尺寸動態計算高度,讓效果更穩定。