マルチデバイス対応とは
iPhoneのデバイスによって画面サイズが異なるため、それぞれの端末で正常に表示するための対応。
マルチデバイス対応方法
主に3つの方法がある。
・オートレイアウト
・プログラムで対応
・storyboard分岐
storyboard分岐が楽だが、チームで開発する時は不都合があるため、プログラムで対応する方法も組み合わせるらしい。
storyboard分岐でマルチデバイス対応する方法
対応したいデバイスのstoryboardを追加。
AppDelegate.swiftとSceneDelegate.swiftに以下のメソッドを追記。
func grabStoryboard() -> UIStoryboard{ var storyboard = UIStoryboard() let height = UIScreen.main.bounds.size.height if height == 667 { storyboard = UIStoryboard(name: "Main", bundle: nil) //iPhone8 }else if height == 736 { storyboard = UIStoryboard(name: "iPhone8plus", bundle: nil) //iPhone8Plus }else if height == 812{ storyboard = UIStoryboard(name: "iPhoneXS", bundle: nil) }else if height == 896{ storyboard = UIStoryboard(name: "iPhoneXSMAX", bundle: nil) }else if height == 1112{ storyboard = UIStoryboard(name: "iPad", bundle: nil) }else{ switch UIDevice.current.model { case "iPnone" : storyboard = UIStoryboard(name: "se", bundle: nil) break case "iPad" : storyboard = UIStoryboard(name: "iPad", bundle: nil) print("iPad") break default: break } } return storyboard }
さらにAppDelegate.swiftとSceneDelegate.swiftに以下を追記。
let storyboard:UIStoryboard = self.grabStoryboard() if let window = window{ window.rootViewController = storyboard.instantiateInitialViewController() as UIViewController? } self.window?.makeKeyAndVisible()
※追記する場所はここ↓
シュミレーターでiPhoneXSを選ぶとiPhoneXSの画面が、iPhone8を選ぶとiPhone8の画面が現れるようになる。