如何根据设备类型(iphone/ipad)在应用程序启动时调用特定的故事板?



我有两个独立的iPad和iPhone故事板,它们有相同的类,出口等,但不同的布局。

我发现我可以用UIScreen.main.traitCollection.userInterfaceIdiom在应用启动时检测设备类型,但现在我需要调用正确的故事板。我怎么做呢?我的方向对吗?我发现所有与这个问题相关的帖子都是8-9年前的,所以我有时甚至不理解语法。提前感谢!

class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let iPhoneStoryboard = UIStoryboard(name: "IPhone", bundle: nil)
let iPadStoryboard = UIStoryboard(name: "IPad", bundle: nil)
let type = UIScreen.main.traitCollection.userInterfaceIdiom

switch type {
case .phone:
// need to call something here
case .pad:
// need to call something here
@unknown default:
fatalError()
}

你必须通过instantiateInitialViewController()instantiateViewController(withIdentifier:)实例化视图控制器

class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let iPhoneStoryboard = UIStoryboard(name: "IPhone", bundle: nil)
let iPadStoryboard = UIStoryboard(name: "IPad", bundle: nil)
let type = UIScreen.main.traitCollection.userInterfaceIdiom

switch type {
case .phone:
window?.rootViewController = iPhoneStoryboard.instantiateInitialViewController()
case .pad:
window?.rootViewController = iPadStoryboard.instantiateInitialViewController()
@unknown default:
fatalError()
}
window?.makeKeyAndVisible()
}
}

你可以尝试将instantiateViewController设置为UINavigationController并将标识符设置为"Ipad"或";Iphone"并将storyboard的第一个控制器设置为UINavigationController的rootviewcontroller,并将初始视图控制器设置为UINavigationController,如…

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

let iPhoneStoryboard = UIStoryboard(name: "IPhone", bundle: nil)
let iPadStoryboard = UIStoryboard(name: "IPad", bundle: nil)
let type = UIScreen.main.traitCollection.userInterfaceIdiom

switch type {
case .phone:

if let IPhone = iPhoneStoryboard.instantiateViewController(withIdentifier: "IPhone") as? UINavigationController {
self.window?.rootViewController = IPhone
}

case .pad:
if let IPad = iPadStoryboard.instantiateViewController(withIdentifier: "IPad") as? UINavigationController {
self.window?.rootViewController = IPad
}
@unknown default:
fatalError()
}
self.window?.makeKeyAndVisible()
self.window?.makeKey()
return true

}

最新更新