gpt4 book ai didi

swift - 如何检查 UIViewController 是否已经显示?

转载 作者:行者123 更新时间:2023-11-30 10:47:29 24 4
gpt4 key购买 nike

我正在开发一个应用程序,它显示带有一些信息的今日扩展。当我点击“今天”扩展时,它会打开应用程序并从根导航到 subview 以显示信息。通常,用户会单击后退箭头返回主视图,但无法判断这是否确实完成。用户可以返回到今天的扩展并再次点击。完成此操作后, subview 将再次打开并包含新信息。如果这样做了很多次,我最终会得到一堆 subview 的实例,并且我必须单击每个实例上的后退按钮才能返回到主视图。

我的问题:是否可以检查 subview 是否已经可见?我希望能够只向其发送更新的信息,而不必显示全新的 View 。

我目前正在通过将 UIViewController 的实例保留在根目录的顶部来处理此问题。如果它不为零,那么我只是将信息传递给它并重绘。如果它为零,那么我调用 performSegue 并创建一个新的。

我只是认为必须有更好的方法来处理这个问题。

编辑:感谢下面的评论者,我想出了这段代码,它似乎可以满足我的需要。

        if let quoteView = self.navigationController?.topViewController as? ShowQuoteVC {
quoteView.updateQuoteInformation(usingQuote: QuoteService.instance.getQuote(byQuoteNumber: quote))
}
else {
performSegue(withIdentifier: "showQuote", sender: quote)
}

这与建议的帖子不同,答案是:

if (self.navigationController.topViewController == self) {
//the view is currently displayed
}

在这种情况下,它不起作用,因为当我从 Today Extension 进入应用程序时,它会转到 Root View Controller 。我需要检查是否正在显示 subview ,并且 self.navigationController.topViewcontroller == self 永远不会工作,因为我没有检查顶部 View Controller 是否是 Root View Controller 。这篇文章中的建议更适用于我想要实现的目标。

最佳答案

您可以使用此扩展来检查当前通过 UIApplication UIViewController 显示的内容:

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

和使用示例:

 if let topController =  UIApplication.topViewController() {
if !topController.isKind(of: MainViewController.self) { //MainViewController- the controller u wish to equal its type
// do action...
}
}

关于swift - 如何检查 UIViewController 是否已经显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55466684/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com