尝试以编程方式更改情节提要时出错

时间:2018-07-14 18:58:34

标签: ios swift uiviewcontroller

我收到错误消息:“使用未解决的标识符'present'”。我正在尝试根据用户设备的高度更改情节提要。

错误出现在以下行:present(viewC, animated: true, completion: nil)

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

    // Override point for customization after application launch.

    var bounds = UIScreen.main.bounds
    var width = bounds.size.width
    var height = bounds.size.height

    if height == 2436 {
        //iphone is iphoneX
        let storyboard = UIStoryboard(name: "ViewControllerX", bundle: nil)
        let viewC = storyboard.instantiateViewController(withIdentifier: "ViewControllerX") as UIViewController
        present(viewC, animated: true, completion: nil)

    return true
}

2 个答案:

答案 0 :(得分:1)

您不能在present中使用AppDelegate,因为这是您需要的UIViewController实例方法

self.window?.rootViewController = viewC 

//

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

    // Override point for customization after application launch.
    if UIScreen.main.bounds.height == 812 {
        //iphone is iphoneX
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let viewC = storyboard.instantiateViewController(withIdentifier: "ViewControllerX") as UIViewController
        self.window?.rootViewController = viewC
     }
     else {

     }

     return true
 }

答案 1 :(得分:0)

由于您处于AppDelegate类中,因此没有可以使用的名为present(_: )的函数。

如果您需要从AppDelegate中显示任何Viewcontroller,请将其添加到窗口中

let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let initialViewController : UIViewController = mainStoryboardIpad.instantiateViewController(withIdentifier: "ViewController") as UIViewController
            self.window = UIWindow(frame: UIScreen.main.bounds)
            self.window?.rootViewController = initialViewController
            self.window?.makeKeyAndVisible()