我使用的是xibs和swift,有没有办法可以使用pushViewController
转到另一个视图并以编程方式返回?
错误:fatal error: unexpectedly found nil while unwrapping an Optional value
我尝试的事情:
2
let rvc: LoginViewController = LoginViewController() self.navigationController!.pushViewController(rvc, animated: true)
如果我从navigationController!
更改为navigationController?
,则不会发生任何事情
答案 0 :(得分:4)
仅当视图控制器位于导航控制器的导航堆栈中时,视图控制器的navigationController
属性(self.navigationController
)才会返回有效的导航控制器对象。
你可以尝试在这张图片中嵌入一个navigationController:
或以编程方式创建它:
let navigationController = UINavigationController(rootViewController: self)
之后你可以推送一个viewController。
评论后更新: 关于你的错误:
It ran into error adding a root view controller <collegeSystem.FirstViewController: 0x7c280330> as a child of view controller:<UINavigationController: 0x7c91bc00>
似乎你试图这样做:
self.window.addSubview(navigationController.view)
而不是:
self.window.rootViewController = navigationController
答案 1 :(得分:2)
试试这个
let vc = LoginViewController(nibName: "LoginViewController", bundle: nil)
self.navigationController!.pushViewController(vc, animated: true)
或试试这个
if let vc = LoginViewController(nibName: "LoginViewController", bundle: nil)
{
self.navigationController!.pushViewController(vc, animated: true)
}
如果您的VC未添加到navigation controller
中,请使用
if let vc = LoginViewController(nibName: "LoginViewController", bundle: nil)
{
self.presentViewController(vc, animated:true, completion:nil)
}
答案 2 :(得分:1)
您尝试访问的导航控制器为零。尝试打印以验证。
print(self.navigationController)
答案 3 :(得分:1)
从xib获取视图控制器对象
YourViewcontroller *viewController = // load from xib
然后
UINavigationController *mainVC = [[UINavigationController alloc] initWithRootViewController:yourController]
并设置根视图控制器
[self.window setRootViewController:mainVC]
现在你可以推
了答案 4 :(得分:0)
let nav = UINavigationController(rootViewController: self)
let rvc: LoginViewController = LoginViewController()
nav.pushViewController(rvc, animated: true)
答案 5 :(得分:0)
试试这个,我在推送到控制器时遇到错误消息,
错误:fatal error: unexpectedly found nil while unwrapping an Optional value
在推送到控制器之前,我们必须对窗口进行初始化,如下面的代码所示
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Do initialisation of window to avoid error message
self.window = UIWindow(frame: UIScreen.main.bounds);
let vc = HomeViewController(nibName: "HomeViewController", bundle: nil)
nav.pushViewController(vc, animated: false)
// Set the window’s root view controller
self.window!.rootViewController = nav
// Present the window
self.window!.makeKeyAndVisible()
return true
}
答案 6 :(得分:0)
为第一个视图创建导航控制器:
Editor
-> Embeded In
-> Navigation Controller
进行选择:
> let vc = NewViewController(nibName: "NewViewController", bundle: nil) > self.navigationController?.pushViewController(vc, animated: true)