【问题标题】:ViewController present does not always work存在的 ViewController 并不总是有效
【发布时间】:2022-01-01 17:59:29
【问题描述】:

我在我的 IOS 应用程序中显示视图控制器时遇到了一些问题。 有时它可以工作并显示视图,但有时我猜当上下文有点不同时它不会工作。调试器中没有错误或警告,它可以从主情节提要中找到 ViewController(至少它不是 nil) 它曾经与 self.present 一起使用,但似乎不再适用了。

  @IBAction func showHistoryButton(_ sender: MDCButton) {
        let exercisesHistoryVC = ExercisesHistoryViewController.instantiate(from: .Main)
        exercisesHistoryVC.modalPresentationStyle = .fullScreen
        let appDeligate = UIApplication.shared.delegate as! AppDelegate
        appDeligate.window?.rootViewController!.present(exercisesHistoryVC,animated: true,completion: nil)
       // parent?.present(exercisesHistoryVC, animated: true, completion: nil)
    }

【问题讨论】:

  • 应该是self.present
  • 如果视图控制器已经在呈现某些东西,它将无法工作。当演示不工作时,我会先检查视图层次结构。
  • 这确实已经是层次结构中的 3e 屏幕,所以这可能是问题所在。是否可以始终在所有内容之上呈现此视图控制器?

标签: swift xcode storyboard


【解决方案1】:

使用如下代码,同时展示新的视图控制器

@IBAction func showHistoryButton(_ sender: MDCButton) {
        let exercisesHistoryVC = ExercisesHistoryViewController.instantiate(from: .Main)
        exercisesHistoryVC.modalPresentationStyle = .fullScreen
        UIApplication.topViewController()?.present(exercisesHistoryVC, animated: false, completion: nil)
 }

extension UIApplication {
    
    static func topViewController(base: UIViewController? = UIApplication.shared.delegate?.window??.rootViewController) -> UIViewController? {
        if let nav = base as? UINavigationController {
            return topViewController(base: nav.visibleViewController)
        }
        if let tab = base as? UITabBarController, let selected = tab.selectedViewController {
            return topViewController(base: selected)
        }
        if let presented = base?.presentedViewController {
            return topViewController(base: presented)
        }
        return base
    }
    
}

【讨论】:

  • @mistert69,检查并告诉我
  • 是的,它现在完美运行!非常感谢,我花了一天多的时间来解决这个问题。
  • 你只需要if let presented = base?.presentedViewController { return topViewController(base: presented) } return base
猜你喜欢
  • 2012-12-26
  • 1970-01-01
  • 1970-01-01
  • 2012-04-23
  • 2015-06-28
  • 2015-12-04
  • 2017-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多