`UITableView` 或繼承自 `UIScrollView` 的視圖在 iOS 7~10 上,內容自動向下偏移 64pt(導航欄高度)或 44pt,導致第一個 Cell 被遮擋或留白。
UIViewController 的屬性 automaticallyAdjustsScrollViewInsets 默認為 YES。當 VC 包含 ScrollView 類視圖時,系統自動設置 contentInset 和 scrollIndicatorInsets 以避開導航欄/工具欄,但常導致佈局異常。
// 在 ViewController 的 viewDidLoad 中
if (@available(iOS 11.0, *)) {
// iOS 11+ 使用 safeAreaLayoutGuide 自動佈局,無需手動調整
} else {
self.automaticallyAdjustsScrollViewInsets = NO;
}
tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever; // iOS 11+
// 或
tableView.insetsContentViewsToSafeArea = NO;
// 僅在需要時手動調整
tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0); // 導航欄高度
tableView.scrollIndicatorInsets = tableView.contentInset;
| iOS 版本 | 推薦做法 |
|---|---|
| ≤ 10 | `self.automaticallyAdjustsScrollViewInsets = NO;` |
| 11 ~ 12 | `tableView.contentInsetAdjustmentBehavior = .never` |
| ≥ 13 | 優先使用 Auto Layout + Safe Area,無需代碼干預 |
iOS 11 前用 `automaticallyAdjustsScrollViewInsets = NO`,iOS 11+ 用 `contentInsetAdjustmentBehavior = .never` 或優先 Auto Layout。現代開發建議最低部署目標設為 iOS 13+,徹底避開該歷史包袱。