您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

UIScrollView 的 contentInset 為什麼會自己變

編輯:iOS 技巧大全

有時候什麼都沒做,UIScrollView 的 contentInset 卻不是 UIEdgeInsetsZero,導致內容位置莫名偏移。這不是 bug,而是系統的行為。

觸發條件

當某個 ViewController 由 UINavigationController 管理,且該控制器的第一個子控件是 UIScrollView 時,系統會自動調節它的 contentInset:

UIEdgeInsetsMake(64, 0, 0, 0) —— 有導航欄
UIEdgeInsetsMake(20, 0, 0, 0) —— 沒有導航欄

如果這個導航控制器又被 UITabBarController 管理,則變為:

UIEdgeInsetsMake(64, 0, 49, 0) —— 同時存在導航欄與標籤欄

這套行為的用意是好的:讓 scrollView 的內容從導航欄下方開始,避免被遮擋。但當你想自己掌控佈局時,它就變成了干擾。

關閉自動調節

self.automaticallyAdjustsScrollViewInsets = NO;

代碼驗證

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (nonatomic, weak) UISwitch *customSwitch;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UISwitch *customSwitch = [[UISwitch alloc] init];
    [self.scrollView addSubview:customSwitch];
    self.customSwitch = customSwitch;

    // 延遲打印,此時 inset 才是最終值
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)),
                   dispatch_get_main_queue(), ^{
        NSLog(@"%@", self.scrollView);
        NSLog(@"%@", NSStringFromUIEdgeInsets(self.scrollView.contentInset));
        NSLog(@"%@", NSStringFromCGRect(self.customSwitch.bounds));
    });
}

// 打印結果
/* 情況一:只有 UINavigationController
   contentOffset: {0, -64}; contentSize: {0, 0}
   {64, 0, 0, 0}
*/
/* 情況二:有 UINavigationController 但隱藏了導航條
   contentOffset: {0, -20};
   {20, 0, 0, 0}
*/
/* 情況三:同時有 UINavigationController 與 UITabBarController
   contentOffset: {0, -64};
   {64, 0, 49, 0}
*/

// 也可以在下面這些時機打印,注意 viewDidLoad 中打印的不是最終值
- (void)viewDidLayoutSubviews {
    // NSLog(@"%@", NSStringFromUIEdgeInsets(self.scrollView.contentInset));
}

- (void)viewDidAppear:(BOOL)animated {
    // NSLog(@"%@", NSStringFromUIEdgeInsets(self.scrollView.contentInset));
}

@end

實踐建議

打印時機很關鍵:在 viewDidLoad 裡讀到的 inset 尚未被系統調整,容易誤判。想在早期關閉自動調節,可以寫在 viewDidLoad 中(此時 scrollView 已加載);若想更謹慎,可在 viewWillLayoutSubviews 裡統一處理。順帶一提,iOS 11 之後這個屬性被標記為過時,取而代之的是 contentInsetAdjustmentBehavior,取值為 Never、Automatic、ScrollableAxes、Always 四種,能更精細地控制僅在可滾動軸上調整。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved