首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

iOS UITableViewCell 內容向下偏移解決:automaticallyAdjustsScrollViewInsets

     編輯:程式設計疑難解答

問題現象

`UITableView` 或繼承自 `UIScrollView` 的視圖在 iOS 7~10 上,內容自動向下偏移 64pt(導航欄高度)或 44pt,導致第一個 Cell 被遮擋或留白。

核心原因

UIViewController 的屬性 automaticallyAdjustsScrollViewInsets 默認為 YES。當 VC 包含 ScrollView 類視圖時,系統自動設置 contentInset 和 scrollIndicatorInsets 以避開導航欄/工具欄,但常導致佈局異常。

解決方案

1. 全局關閉(推薦,iOS 11+ 已廢棄此屬性)

// 在 ViewController 的 viewDidLoad 中
if (@available(iOS 11.0, *)) {
    // iOS 11+ 使用 safeAreaLayoutGuide 自動佈局,無需手動調整
} else {
    self.automaticallyAdjustsScrollViewInsets = NO;
}

2. 針對單個 ScrollView 關閉

tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever; // iOS 11+
// 或
tableView.insetsContentViewsToSafeArea = NO;

3. 手動設置 contentInset(舊版本兼容)

// 僅在需要時手動調整
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,無需代碼干預

調試技巧

  • 在 View Debugger 中檢查 `contentInset`、`adjustedContentInset`、`safeAreaInsets` 數值。
  • 打印 `tableView.contentInset` 觀察是否被自動修改。
  • 給 Cell 背景色區分偏移區域。

總結

iOS 11 前用 `automaticallyAdjustsScrollViewInsets = NO`,iOS 11+ 用 `contentInsetAdjustmentBehavior = .never` 或優先 Auto Layout。現代開發建議最低部署目標設為 iOS 13+,徹底避開該歷史包袱。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved