如何在iOS中使用代码切换视图控制器?

时间:2017-06-28 18:27:02

标签: ios swift

let SecondViewController = 
self.storyboard?.instantiateViewController(withIdentifier: 
"SecondViewController") as! SecondViewController

self.navigationController?.pushViewController(SecondViewController, 
animated: true)

出于某种原因,这不起作用。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

替换

self.navigationController?.pushViewController(SecondViewController, 
animated: true)

self.navigationController?.present(SecondViewController, animated: true, completion: nil)

编辑:要避免选项,您还应该执行以下操作之一:

guard let navController = self.navigationController else { return }
navController.present(SecondViewController, animated: true, completion: nil)

if let nacVontroller = self.navigationController {
    navController.present(SecondViewController, animated: true, completion: nil)
}

Edit2:您还应该避免使用上述方法之一强制解包SecondViewController。虽然这不是你当前的问题。