最新iOS 11 & iPhone X適配方案傳送門:10分鐘適配 iOS11 & iPhoneX
##發現問題
升級Xcode 9 + iOS 11後,發現原本沒問題的collectionView和tableView像是中了風一樣,頭部重新整理UI出現了錯亂。
查閱發現 iOS11棄用了automaticallyAdjustsScrollViewInsets
屬性,新增contentInsetAdjustmentBehavior
來替代它
關於 contentInsetAdjustmentBehavior
@available(iOS 11.0, *)
public enum UIScrollViewContentInsetAdjustmentBehavior : Int {
case automatic // Similar to .scrollableAxes, but will also adjust the top & bottom contentInset when the scroll view is owned by a view controller with automaticallyAdjustsScrollViewContentInset = YES inside a navigation controller, regardless of whether the scroll view is scrollable
case scrollableAxes // Edges for scrollable axes are adjusted (i.e., contentSize.width/height > frame.size.width/height or alwaysBounceHorizontal/Vertical = YES)
case never // contentInset is not adjusted
case always // contentInset is always adjusted by the scroll view's safeAreaInsets
}
複製程式碼
UIScrollViewContentInsetAdjustmentBehavior 是一個列舉型別,值有以下幾種:
-automatic
和scrollableAxes一樣,scrollView會自動計算和適應頂部和底部的內邊距並且在scrollView 不可滾動時,也會設定內邊距.
-scrollableAxes
自動計算內邊距.
-never
不計算內邊距
-always
根據safeAreaInsets 計算內邊距
很顯然,我們這裡要設定為 never
##開始適配 ####OC 中
if (@available(iOS 11.0, *)){
_tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
_tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);//導航欄如果使用系統原生半透明的,top設定為64
_tableView.scrollIndicatorInsets = _tableView.contentInset;
}
複製程式碼
####swift 中
if #available(iOS 11.0, *) {
tableView.contentInsetAdjustmentBehavior = .never
tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0)//導航欄如果使用系統原生半透明的,top設定為64
tableView.scrollIndicatorInsets = tableView.contentInset
}
複製程式碼
凡是Scrollview 及 Scrollview子類都會有適配問題,整個工程使用了無數Scrollview的你心理陰影面積一定不小,別擔心,其實可以一行程式碼解決問題:
// AppDelegate 進行全域性設定
if (@available(iOS 11.0, *)){
[[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
}
複製程式碼
####終於又迴歸原來的效果啦

更多程式碼可參考 https://github.com/XuYang8026/UniversalProject
以上屬於臭碼農原創,若有雷同屬巧合,如有錯誤望指正,轉載請標明來源和作者。 by:臭碼農