バイトをしていない時のストレスのたまらなさは異常。
コンちゃ、TOSHです。
今日は、
iPhoneのサイズに合わせて、storyboardを変更していく方法を紹介したいと思います!
本来はAutoLayoutを使うのがいいのかもしれませんが、AutoLayoutようわからんとか、すでたくさんパーツを置いてしまい、今から切り替えるのは難しいという人向けに紹介したいと思います!
やり方
- これは、初めから存在する、
AppDelegate.swift
というファイルに書き込んでいきます!
仕組みとしては、まず、iPhoneの画面サイズを取得し、if文で画面サイズごとに動作を分岐させる感じです。 - まずは画面を取得し、if文で分岐させる
AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let display: CGRect = UIScreen.main.bounds
// 取得ディスプレイに対応したStoryBoardをrootViewController(最初に表示されるもの)にする。
if display.size.height == 568 {
// iPhone 4S の場合 (Unit is Point.)
let storyboard = UIStoryboard(name: "Sub", bundle: nil)
let rootViewController: UIViewController? = storyboard.instantiateInitialViewController()
window?.rootViewController = rootViewController
}
else if display.size.height == 667 {
// iPhone 6 の場合
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let rootViewController: UIViewController? = storyboard.instantiateInitialViewController()
window?.rootViewController = rootViewController
}
else if display.size.height == 736 {
// iPhone 6 Plus の場合
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let rootViewController: UIViewController? = storyboard.instantiateInitialViewController()
window?.rootViewController = rootViewController
}
}
- 対応するStoryboardを作成する
今回の場合では、iPhone5Sのサイズの場合、Sub
というUIStoryboard
を読み込み、
iPhone6や6 Pusのサイズの場合は、Main
というStoryboard
を読みこむ設定をしてるので、
Main.Storyboard
とSub.Storyboard
を作成してあげましょう!
これで、完成です!
いろんな実機で読み込んでみて、きちんと読み込めるのか確認してみましょう!
以上、TOSHでした!