gpt4 book ai didi

ios - 为什么我们不能在以编程方式设置初始 viewController 时以编程方式在 viewController 之间跳转?

转载 作者:搜寻专家 更新时间:2023-11-01 06:16:55 28 4
gpt4 key购买 nike

我只使用了两个 viewController,比如 viewControllerAviewControllerB。通过在AppDelegate.swift中使用如下代码,当App第一次启动时,会将viewControllerA设置为初始viewController,从第二次启动开始, viewControllerB 将被设置为初始 viewController。

class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
let defaultss = UserDefaults.standard
if (!defaultss.bool(forKey: "firstTimes")) {
self.window = UIWindow(frame: UIScreen.main.bounds)

let storyboard = UIStoryboard(name: "Main", bundle: nil)

let initialViewController = storyboard.instantiateViewController(withIdentifier: "ViewControllerA")

self.window?.rootViewController = initialViewController
self.window?.makeKeyAndVisible()

defaultss.set(true, forKey: "firstTimes") //set the key so it never executes again
} else
{

self.window = UIWindow(frame: UIScreen.main.bounds)

let storyboard = UIStoryboard(name: "Main", bundle: nil)

let initialViewController = storyboard.instantiateViewController(withIdentifier: "ViewControllerB")

self.window?.rootViewController = initialViewController
self.window?.makeKeyAndVisible()
}
return true

}

它工作正常。但是如果我使用这段代码,那么我无法以编程方式在 viewController 之间跳转,无论是从 AB 还是从 BA,使用以下代码。

import UIKit

class ViewControllerA: UIViewController {


override func viewDidLoad()
{
super.viewDidLoad()
}

@IBAction func buttonA(_ sender: Any)
{
let ViewControllerB = storyboard?.instantiateViewController(withIdentifier: "ViewControllerB") as! ViewControllerB
navigationController?.pushViewController(ViewControllerB, animated: true)
}


}

import UIKit

class ViewControllerB: UIViewController {

override func viewDidLoad()
{
super.viewDidLoad()

}


@IBAction func buttonB(_ sender: Any)
{
let ViewControllerA = storyboard?.instantiateViewController(withIdentifier: "ViewControllerA") as! ViewControllerA
navigationController?.pushViewController(ViewControllerA, animated: true)
}

}

我怎样才能同时实现这两者,我应该能够检测到第一次启动并设置初始 viewController,而且我还应该能够以编程方式在 viewController 之间跳转。

我正在使用 Xcode 8.2、Swift 3.0。

提前致谢。

最佳答案

在 App delegate 中执行此操作

let navC = UINavigationController(rootViewController: initialViewController)
self.window?.rootViewController = navC

代替

self.window?.rootViewController = initialViewController

关于ios - 为什么我们不能在以编程方式设置初始 viewController 时以编程方式在 viewController 之间跳转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42692550/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com