我想在用户登录时切换加载ViewController。 问题:当用户等于" true" ...
时,视图没有改变提前谢谢!!
override func viewDidLoad() {
super.viewDidLoad()
var user: String?
user = UserDefaults.standard.value(forKey: "loginSuccessfull") as? String
if user == "true" {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondView") as UIViewController!
self.show(vc!, sender: vc)
}
// Do any additional setup after loading the view, typically from a nib.
}
答案 0 :(得分:4)
从viewDidLoad
方法中删除代码并使用以下方法。
override func viewDidAppear() {
guard let user = UserDefaults.standard.string(forKey: "loginSuccessfull"), user == "true" else {
return
}
let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondView")!
self.present(vc, animated: true)
}
答案 1 :(得分:3)
您应该在viewWillAppear()
或viewDidAppear()
中放置显示第二个View Controller的代码。
override func viewDidAppear() {
super.viewDidAppear()
var user: String?
user = UserDefaults.standard.value(forKey: "loginSuccessfull") as? String
if user == "true" {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondView") as UIViewController!
self.show(vc!, sender: vc)
}
// Do any additional setup after loading the view, typically from a nib.
}
原因是在viewDidLoad()
期间,您的ViewController的某些属性尚未定义,并且尚未准备好呈现另一个ViewController。
答案 2 :(得分:1)
你需要让它成为异步,不需要任何延迟,就像这样:
override func viewDidLoad() {
super.viewDidLoad()
var user: String?
user = UserDefaults.standard.value(forKey: "loginSuccessfull") as? String
DispatchQueue.main.asyncAfter(deadline: .now()) {
if user == "true" {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondView") as UIViewController!
self.show(vc!, sender: vc)
}
}
}
答案 3 :(得分:0)
不是在viewDidLoad中编写逻辑,而是在呈现当前viewcontroller
之前编写它e.g。 如果要在应用程序启动时检查它,请检查用户是否已登录didFinishLaunching方法并相应地设置rootViewController。
如果想要从其他一些viewController中呈现它,首先检查用户登录状态并相应地显示viewcontroller而不是check in viewDidLoad。
此外,您可以通过在延迟一段时间后执行操作来呈现视图控制器。
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
// present view contoller
}