遇到「一張滿版背景圖,上面要在固定位置放好幾顆按鈕,而且得適配各種機型」的需求時,該怎麼做?以下是我的解法。

問題具體來說是:在上圖這張滿版背景上,要在 M、U、R、P 以及「訪問官方網站」這五個位置各放一顆按鈕,並在 3.5 吋、4.0 吋、4.7 吋、5.5 吋等各種螢幕上都維持正確的相對位置。
第一步,在 Storyboard 中拖入四個 View Controller,分別把 Screen Size 設為 3.5、4.0、4.7、5.5 吋。
第二步,為每個場景設定對應的背景圖,並在各自的位置擺好按鈕。
第三步,執行時判斷螢幕高度,動態載入對應的場景(以下為 Swift 範例):
let screenHeight = UIScreen.mainScreen().bounds.size.height
var storyBoards: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) as UIStoryboard
if (screenHeight <= /* 3.5 吋高度 */) {
viewCon = storyBoards.instantiateViewControllerWithIdentifier("FirstViewController") as! FirstViewController
} else if (screenHeight <= /* 4.0 吋高度 */) {
viewCon = storyBoards.instantiateViewControllerWithIdentifier("FirstViewController") as! FirstViewController
} else if (screenHeight <= /* 4.7 吋高度 */) {
viewCon = storyBoards.instantiateViewControllerWithIdentifier("FirstViewController") as! FirstViewController
} else if (screenHeight <= /* 5.5 吋高度 */) {
viewCon = storyBoards.instantiateViewControllerWithIdentifier("FirstViewController") as! FirstViewController
}
var naviCon: MainNavigationController = MainNavigationController(rootViewController: viewCon)
優點很直接:每個尺寸都能精準對位,設計師怎麼稿就怎麼擺,不必跟約束系統纏鬥。缺點也很明顯——螢幕尺寸一多,場景數量會線性成長,後續維護每個場景的成本不低。
因此實務上更常採用另外兩種策略。一是相對約束:把按鈕的位置相對於背景圖或父視圖設定比例約束(例如 leading 佔寬度的 20%),讓 Auto Layout 自動換算,一個場景就能吃所有尺寸。二是單張可拉伸圖:把背景設計成「中間可橫向/縱向延展、四角固定」的九宮格素材,用 resizableImageWithCapInsets: 處理,再按約束擺放按鈕。這樣即使未來出現新的螢幕比例(如 iPhone X 之後的瀏海螢幕),也不必再新增場景。
若你的 App 只需要支援少數幾個固定機型、且背景圖是設計好的整張稿,那麼本文的多場景做法依然是最省事的選擇。