3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

iPhoneの画面サイズに合わせてStoryboardを変更する

Posted at

バイトをしていない時のストレスのたまらなさは異常。
コンちゃ、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.StoryboardSub.Storyboardを作成してあげましょう!

これで、完成です!

いろんな実機で読み込んでみて、きちんと読み込めるのか確認してみましょう!
以上、TOSHでした!

3
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?