xcode 在 ViewDidLoad 中执行 Segue
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45653825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Perform Segue in ViewDidLoad
提问by Paal Aune
I`m trying to perform a segue if its the first time the app is loading. I can see my print message in the debugger, but the Perform Segue is not working. I don't get any errors. Can somebody please tell me whats wrong?
如果是第一次加载应用程序,我会尝试执行 segue。我可以在调试器中看到我的打印消息,但 Perform Segue 不起作用。我没有收到任何错误。有人可以告诉我有什么问题吗?
import UIKit
import LocalAuthentication
let isFirstLaunch = UserDefaults.isFirstLaunch()
extension UserDefaults {
// check for is first launch - only true on first invocation after app install, false on all further invocations
// Note: Store this value in AppDelegate if you have multiple places where you are checking for this flag
static func isFirstLaunch() -> Bool {
let hasBeenLaunchedBeforeFlag = "hasBeenLaunchedBeforeFlag"
let isFirstLaunch = !UserDefaults.standard.bool(forKey: hasBeenLaunchedBeforeFlag)
if (isFirstLaunch) {
UserDefaults.standard.set(true, forKey: hasBeenLaunchedBeforeFlag)
UserDefaults.standard.synchronize()
}
return isFirstLaunch
}
}
class loginVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if isFirstLaunch == false {
performSegue(withIdentifier: "setPassword", sender: self)
print("testFalse") }
else {
performSegue(withIdentifier: "setPassword", sender: self)
print("testTrue")}
// Do any additional setup after loading the view, typically from a nib.
}
回答by Smartcat
You can't use performSegue() from within viewDidLoad(). Move it to viewDidAppear().
您不能在 viewDidLoad() 中使用 performSegue()。将其移至 viewDidAppear()。
At viewDidLoad() time, the current view isn't even attached to the window yet, so it's not possible to segue yet.
在 viewDidLoad() 时,当前视图甚至还没有附加到窗口,所以还不可能继续。
回答by Philip
I think you can also put your segue into a Dispatch.main.async
我想你也可以把你的 segue 放到一个 Dispatch.main.async
DispatchQueue.main.async {
if isFirstLaunch == false {
performSegue(withIdentifier: "setPassword", sender: self)
print("testFalse")
} else {
performSegue(withIdentifier: "setPassword", sender: self)
print("testTrue")
}
}
回答by cohen72
You can also use a different approach - change the main window's rootViewController
to the view controller of your choice depending on isFirstLaunch
boolean
您还可以使用不同的方法 -rootViewController
根据isFirstLaunch
布尔值将主窗口更改为您选择的视图控制器
UIApplication.shared.keyWindow?.rootViewController = setPasswordViewController
UIApplication.shared.keyWindow?.rootViewController = setPasswordViewController