【问题标题】:UIViewController setting new root view when click buttonUIViewController 单击按钮时设置新的根视图
【发布时间】:2020-06-28 21:29:41
【问题描述】:

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

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

  @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
        }
    }

但是,当我在刺激器中运行它时,当我单击它时,该按钮不会做任何事情。请注意,我使用的是 Tab Bar Controller,所以我尝试将根设置为 UIBarController,但这也不起作用。

【问题讨论】:

  • 为什么要将此块执行到DispatchQueue.main.async 中?

标签: swift xcode uiviewcontroller


【解决方案1】:

在您的 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)
    }
}

【讨论】:

  • 我尝试了您的代码并收到此行的错误,我已经评论了收到的错误:let window = UIApplication.shared.delegate!.window!! //Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value 我认为当我将代码连接到 JSON 并应用逻辑等时,将调度放入 for 会很好。
  • 我忘了添加这个。在您的 AppDelegate 中,添加此属性: final var window: UIWindow?
  • @TomoNorbert 我刚刚意识到代码没有在底部显示我的 TabBar?
  • 哦,如果你想改变UITabBarController里面的viewControllers,使用tabBarController.setViewControllers([home], animated: true)来替换viewcontrollers
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-11
  • 1970-01-01
  • 2013-06-10
相关资源
最近更新 更多