萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 螢幕旋轉適配實戰:Auto Layout 時代的佈局更新策略

舊時代:手動 Frame 計算(不推薦)


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
    return orientation != UIInterfaceOrientationPortraitUpsideDown;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)orientation duration:(NSTimeInterval)duration {
    if (UIInterfaceOrientationIsPortrait(orientation)) {
        // 直向佈局
        self.button1.frame = CGRectMake(20, 20, 125, 125);
        self.button2.frame = CGRectMake(175, 20, 125, 125);
        // ...
    } else {
        // 橫向佈局
        self.button1.frame = CGRectMake(20, 20, 125, 125);
        self.button2.frame = CGRectMake(20, 155, 125, 125);
        // ...
    }
}

缺點:硬編碼座標、設備適配差、Split View 不支援、維護地獄。

現代標準:Auto Layout + Size Classes + Trait Collections

1. Storyboard / XIB 中配置

  • 為每個約束設置 Size Class 特定常數(wCompact hRegular / wRegular hCompact / wRegular hRegular 等)
  • 使用 Vary for Traits 針對不同尺寸類調整佈局、字體、甚至隱藏/顯示視圖

2. 代碼中動態響應


- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    
    [coordinator animateAlongsideTransition:^(id context) {
        // 動畫過程中同步更新約束/佈局
        [self updateConstraintsForSize:size];
        [self.view layoutIfNeeded];
    } completion:nil];
}

- (void)updateConstraintsForSize:(CGSize)size {
    BOOL isLandscape = size.width > size.height;
    self.stackView.axis = isLandscape ? UILayoutConstraintAxisHorizontal : UILayoutConstraintAxisVertical;
    self.collectionViewLayout.itemSize = isLandscape ? CGSizeMake(200, 150) : CGSizeMake(150, 200);
    // 更新其他約束常數...
}

3. Trait Collection 變化監聽(iOS 8+)


- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];
    if (![self.traitCollection containsTraitsInCollection:previousTraitCollection]) {
        // Size Class 發生變化(如 iPad 分屏、iPhone 旋轉、Mac Catalyst 視窗縮放)
        [self updateLayoutForTraitCollection:self.traitCollection];
    }
}

關鍵最佳實踐

  1. 優先使用 Stack View / Collection View / Grid Layout:聲明式佈局自動適配旋轉
  2. 避免硬編碼寬高:使用相對約束、內邊距、安全區域
  3. 安全區域適配:view.safeAreaLayoutGuide (iOS 11+) 自動處理刘海、Home Indicator、來電條
  4. 橫屏專用佈局:traitCollection.horizontalSizeClass == .regular 區分 iPad/Plus 橫屏與普通 iPhone 橫屏
  5. 測試矩陣:iPhone SE/13/14/15/Plus/Pro Max、iPad Mini/Air/Pro、Split View 1/3、2/3、1/2、橫豎向、動態字體

避坑指南

  • ❌ 在 viewDidLoad 讀取 interfaceOrientation 決定初始佈局
  • ❌ 手動計算 frame 並 setFrame: 破壞 Auto Layout
  • ❌ 忽略 viewWillTransitionToSize: 中的 transitionCoordinator 動畫同步
  • ✅ 使用 viewWillTransitionToSize: + animateAlongsideTransition:
  • ✅ 利用 Size Class 在 IB 中聲明式配置差異化佈局
  • ✅ 啟用 UIRequiresFullScreen = NO 支援 iPad 多任務
copyright © 萬盛學電腦網 all rights reserved