Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift UIViewController在单击按钮时设置新的根视图_Swift_Xcode_Uiviewcontroller - Fatal编程技术网

Swift UIViewController在单击按钮时设置新的根视图

Swift UIViewController在单击按钮时设置新的根视图,swift,xcode,uiviewcontroller,Swift,Xcode,Uiviewcontroller,我有一个按钮的代码,当点击该按钮时,会将用户带到主页,该主页是我命名为“HomePageViewController”的UIViewController,我还将该类设置为如下所示: 按钮代码位于名为“SignenViewController”的第一个(初始控制器)UIViewController中,单击该按钮时,我希望HomePageViewController替换SignenViewController: @IBAction func btnSignInPressed(_ sender:

我有一个按钮的代码,当点击该按钮时,会将用户带到主页,该主页是我命名为“HomePageViewController”的UIViewController,我还将该类设置为如下所示:

按钮代码位于名为“SignenViewController”的第一个(初始控制器)UIViewController中,单击该按钮时,我希望HomePageViewController替换SignenViewController:

  @IBAction func btnSignInPressed(_ sender: UIButton) {
        // if true take to home page
        DispatchQueue.main.async {
            let home = self.storyboard?.instantiateViewController(identifier: "HomePageViewController") as!
            HomePageViewController
            
            // replace the homepage as the root page
            let appDelegate = UIApplication.shared.delegate
            appDelegate?.window??.rootViewController = home
        }
    }

然而,当我在刺激器中运行这个按钮时,当我点击它时,该按钮没有任何作用。请注意,我使用的是选项卡栏控制器,因此我尝试将root设置为UIBarController,但这也不起作用。

在appDelegate中,添加属性:

final var window: UIWindow?
这样说吧

@IBAction func btnSignInPressed(_ sender: UIButton) {
    // if true take to home page
    DispatchQueue.main.async {
        let home = self.storyboard?.instantiateViewController(identifier: "HomePageViewController") as!
            HomePageViewController

        let window = UIApplication.shared.delegate!.window!!
        window.rootViewController = nil
        window.rootViewController = home
        
        UIView.transition(with: window, duration: 0.4, options: [.transitionCrossDissolve], animations: nil, completion: nil)
    }
}


为什么要将此块执行到
DispatchQueue.main.async
?我尝试了您的代码并收到了此行的错误,我已对收到的错误进行了注释:let window=UIApplication.shared.delegate!。窗户//线程1:致命错误:在解包一个可选值时意外发现nil,我认为在将代码连接到JSON并应用逻辑等时最好加入分派。我忘了添加这个。在您的AppDelegate中,添加以下属性:final var window:UIWindow?@TomoNorbert我刚刚意识到代码没有在底部显示我的选项卡栏?哦,如果您想更改UITabBarController中的ViewController,请使用tabBarController.SetViewController([home],animated:true)替换ViewController