gpt4 book ai didi

ios - 在单独的类文件中定义 UIAlert,然后从任何 View Controller 调用它

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

为了避免重复代码,我想创建一个单独的类文件来处理我的应用程序中的所有错误(主要是从后端 block 返回),并在用户可以关闭的警报弹出窗口中将它们呈现给用户。所以我创建了一个类,并将其放入:

import Foundation

class Errors {

func errors(errorText: String, currentViewController: UIViewController) {

var alert = UIAlertController(title: "There was an error", message: errorText, preferredStyle: UIAlertControllerStyle.Alert)

alert.addAction(UIAlertAction(title: "Close", style: .Default, handler: nil))


currentViewController.presentViewController(alert, animated: true, completion: nil)


}
}

然后当从任何 viewController 调用此函数时,我会这样做:

            Errors().errors("Error text", currentViewController: GameScreenViewController)

这行不通,编译器要我在 GameScreenViewController 之后添加 (),这会导致应用程序行为不正常。

我想这不是正确的做法,请问您能否建议如何正确地做到这一点。请用 Swift 回答。

最佳答案

您需要使用“self”而不是 GameScreenViewController 作为您希望显示错误的 View Controller 中的第二个参数来调用它。

您当前传递的不是对象,而只是类名。

class GameScreenViewController : UIViewConroller {

// your viewcontroller logic

func showError(){
// try this:
Errors().errors("Error text", currentViewController: self)
}

}

关于ios - 在单独的类文件中定义 UIAlert,然后从任何 View Controller 调用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27102300/

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