您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS UI 適配入門:從 frame 到 autoresizingMask

編輯:iOS 相關資訊

自從 iPhone 5 拉長了螢幕之後,同一套 App 要同時跑在 4 吋、4.7 吋、5.5 吋等不同尺寸上,UI 的「靈活操控」就變得格外重要。本文整理了几个在該年代非常實用的老 API,帶你理解如何用最樸素的方式完成多螢幕適配。

從 view 說起

以下程式碼皆為 ARC 環境。手動建立 view 時,通常都在 loadView 方法中初始化 viewController 的 self.view。這裡先介紹兩個關鍵 API:

  1. [UIScreen mainScreen].bounds:螢幕的 bounds。
  2. [UIScreen mainScreen].applicationFrame:App 的 frame,當 statusBar 隱藏時,它跟 bounds 實際上是一樣的。

我一般這樣建立 view:

self.view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];

此時 view 的 frame 在 iPhone 5 是 (0, 20, 320, 548),在更早的 iPhone 則是 (0, 20, 320, 460)。

之後,self.view 的 frame 會在 viewWillAppear 方法中自動變化、適配螢幕尺寸。也就是說,如果你有 navigationBar,此時 view 的 frame 會是 (0, 20, 320, 504)(iPhone 5)。以前我都是在 loadView 時手動把高度減掉 44,不知道有沒有人跟我一樣繞過遠路。

一句話總結:controller 的 self.view 會在 viewWillAppear 時,把自己設為「扣除 statusBar 與 navigationBar 之後、填滿螢幕」的尺寸;即使沒有它們,self.view 依然會填滿整個螢幕。

關鍵屬性:autoresizingMask

接下來是 UIView 上一個適配利器——autoresizingMask。它的作用是:當 superView 的 frame 變化後,決定自身在 superView 中的位置或大小如何變化。列舉如下:

enum {
    UIViewAutoresizingNone                     = 0,
    UIViewAutoresizingFlexibleLeftMargin       = 1 << 0,
    UIViewAutoresizingFlexibleWidth            = 1 << 1,
    UIViewAutoresizingFlexibleRightMargin      = 1 << 2,
    UIViewAutoresizingFlexibleTopMargin        = 1 << 3,
    UIViewAutoresizingFlexibleHeight           = 1 << 4,
    UIViewAutoresizingFlexibleBottomMargin     = 1 << 5
};
typedef NSUInteger UIViewAutoresizing;

舉個例子:假設背景中有個 button,你希望它無論何時距離背景底部的距離都固定,那就把它的 autoresizingMask 設為 UIViewAutoresizingFlexibleTopMargin。

來看 UIViewAutoresizingFlexibleTopMargin 的定義:The view resizes by expanding or shrinking in the direction of the top margin. 也就是說,它在 superView 中距離頂部的位置是可變的。

如果同時設定 UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin,那麼它在 superView 中的新位置,會是舊位置乘以一個比例因數得出。比例因數為:

(superView 當前高度 - 它的高度) / (superView 原高度 - 它的高度)

實戰:適配不同螢幕

有了這兩個知識點,就能輕鬆適配 iPhone 5 與舊尺寸的螢幕。例如某個 view B 裡有個元素 A,你希望 A 無論在 iPhone 5 還是 4s 上,都距離 B 的底部 20px,那麼只需把 A 的 autoresizingMask 設為 UIViewAutoresizingFlexibleTopMargin,並在 controller 的 viewWillAppear 中設定 B 的新 frame 即可。

在 Auto Layout 普及之前,這套「frame + autoresizingMask」就是多螢幕適配的標準打法。理解它的原理,有助於你看懂老專案,也能更透徹地認識 iOS 布局的演進。

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