这里我在一个 viewController 中,我想转到另一个 id 为 ViewUSRControllerID 的 viewController 这是我的代码。用户登录后移动的目标:
@IBAction func login_btn(_ sender: UIButton) {
if username_txt.text == "" || password_txt.text == "" {
//print("empty")
let alert = UIAlertController(title: "Error", message: "you must fill up both username and password", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}else if (username_txt.text! == "admin" && password_txt.text! == "Passw0rd" ){
print("login successful")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let cr = storyboard.instantiateViewController(withIdentifier: "ViewUSRControllerID")
self.navigationController?.pushViewController(cr, animated: true)
}
}
输出是我可以打印登录成功
但没有进行推送。为了测试,我替换了:
self.navigationController?.pushViewController(cr, animated: true)
与: self.present(cr, 动画: true)
在它工作正常。但为什么插入不起作用呢?
最佳答案
在你的代码中
self.navigationController?.pushViewController(cr, animated: true)
self.navigationController?
是 UIViewController
的可选属性,如果您的 LoginViewController
嵌入了 UINavigationController
,那么您可以使用 UINavigationController
方法 pushViewController
并且此方法从 LoginViewController
推送 ViewUSRController
。
因此,如果您使用的是 Storyboard,那么在 LoginViewController
中嵌入 UINavigationController
就非常简单。
步骤:-
1.在 Storyboard中选择LoginViewController
。
2.xCpode顶部面板“Editor”
3.选择“嵌入”-> UINavigationController
看起来像这样
关于ios - 推送新的 View Controller (以编程方式)不起作用?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43485878/