gpt4 book ai didi

ios - 从另一个类调用警报 View ,但不在层次结构中

转载 作者:行者123 更新时间:2023-11-28 21:43:34 25 4
gpt4 key购买 nike

我正在尝试从 View Controller 中的一个类调用函数:

var rate = RateMyApp.sharedInstance 
rate.showRatingAlert()

在 RateMyApp 类中,我调用警报 View :

 var window: AnyObject = UIApplication.sharedApplication().keyWindow!;
var vc = window.rootViewController;
vc?!.presentViewController(alert, animated: true, completion: nil)

但是,没有显示警报,并且有一种警告:

 Warning: Attempt to present <UIAlertController: 0x15fe3dcf0> on <drawtext.ViewController: 0x16002a800> whose view is not in the window hierarchy!

这种情况时有发生,如果隐藏应用程序然后多次打开它,有时会显示警告。

什么会导致这种奇怪的行为?

最佳答案

在使用 UIAlertController 时,它应该从 View 层次结构中最顶层的 ViewController 呈现。

所以我建议:

var rate = RateMyApp.sharedInstance 
rate.showRatingAlert(self)

在 RateMyApp 类中:

func showRatingAlert(sender:UIViewController){
//..... your UIAlertController here
sender.presentViewController(alert, animated: true, completion: nil)
}

一般来说,函数 presentViewController(:_) 应该只从最顶层的 View Controller 调用。

你可以像这样为它创建一个扩展:

extension UIViewController {
@warn_unused_result
static func topViewController(base: UIViewController? = UIApplication.sharedApplication().windows.first?.rootViewController) -> UIViewController? {

if let nav = base as? UINavigationController {
return topViewController(nav.visibleViewController)
}

if let tab = base as? UITabBarController {
let moreNavigationController = tab.moreNavigationController

if let top = moreNavigationController.topViewController where top.view.window != nil {
return topViewController(top)
} else if let selected = tab.selectedViewController {
return topViewController(selected)
}
}

if let presented = base?.presentedViewController {
return topViewController(presented)
}

if let splitVC = base as? UISplitViewController {
if let lastVC = splitVC.viewControllers.last {
return topViewController(lastVC)
}
else {
return splitVC
}
}

if let lastChildVC = base?.childViewControllers.last {
return topViewController(lastChildVC)
}

return base
}
}

您可以按如下方式调用警报:

func showRatingAlert() {
if let vc = UIViewController.topViewController() {
vc.presentViewController(alert, animated: true, completion: nil)
}
}

关于ios - 从另一个类调用警报 View ,但不在层次结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31157448/

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