gpt4 book ai didi

ios - 其他文件中的ViewController

转载 作者:行者123 更新时间:2023-11-30 13:55:28 24 4
gpt4 key购买 nike

我是 Swift 2 的新手。我尝试在另一个文件中创建 UIAlertController。

这是我的代码:

class my_view_error: UIViewController {

func my_error(my_title: String, my_message: String) {
let alertController = UIAlertController(title: my_title, message: my_message, preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in }
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {}
}
}

我收到编译时错误:

Warning: Attempt to present on whose view is not in the window hierarchy!

我的问题是,是否可以在 ViewController.swift 之外的文件中创建 ViewController?

最佳答案

您创建了一个名为 my_view_errorUIViewController 子类。 UIViewController 方法 presentViewController 期望在调用该方法时 self (my_view_error)出现在屏幕上.

您的 my_error 函数非常好,但应该将其移动到实际位于屏幕上的 View Controller 。不需要仅仅为了呈现 UIAlertController 而创建 UIViewController。事实上,UIAlertController 一个UIViewController,并且不需要自定义 View Controller 的帮助。

就像任何 View Controller 一样,呈现警报的 View Controller 必须位于屏幕上才能执行呈现。

每个 View Controller 可能有自己的 .swift 文件。不过,无需为 UIAlertController 创建一个。

这是该函数的一个版本,它在 UIApplication 上使用 rootViewController 来获取当前屏幕上的 View Controller ,然后使用它来显示您的警报:

func my_error(my_title: String, my_message: String) {
let alertController = UIAlertController(title: my_title, message: my_message, preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in }
alertController.addAction(OKAction)

// Uses UIApplication.sharedApplication().keyWindow!.rootViewController! instead of self
UIApplication.sharedApplication().keyWindow!.rootViewController!.presentViewController(alertController, animated: true) {}
}

关于ios - 其他文件中的ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33684664/

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