gpt4 book ai didi

Swift;将自定义 View Controller 转换到 View Controller

转载 作者:行者123 更新时间:2023-11-28 15:14:35 24 4
gpt4 key购买 nike

我有一个为我处理警报的结构。它只有一个功能:

func presentAlert(_ title:String, _ message:String, _ presenter:ViewController) {

let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
myAlert.addAction(okAction)
presenter.present(myAlert, animated:true, completion:nil)
}

我可以从 View Controller 调用它。但是在子类 AddTopicViewController 上我收到一个错误:

myController.alert.presentAlert("Form errors", strErrMsg, self)

//error from compiler
Cannot convert value of type 'AddTopicViewController' to expected argument type 'ViewController'

那么,两个问题:

由于 AddTopicVC 是 VC 的子类,我认为它会通过 对于需要 VC 的东西。显然那一点是错误的。可以 有人解释我的逻辑缺陷吗?

关于如何实现我的目标有什么建议吗?该应用程序有很多 每当用户未输入时都会显示验证和警报 需要的数据,但所有的 View Controller 都是子类。我试过 用函数扩展 viewcontroller 但子类给出了 该方法不可用的错误。

感谢您的帮助。

最佳答案

最简单的方法是使用假定的基类 UIViewController,所有 View Controller 都继承自该基类。

func presentAlert(_ title:String, _ message:String, _ presenter:UIViewController)

或者使用 UIViewController 的扩展

extension UIViewController {

func presentAlert(_ title:String, _ message:String) {

let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
myAlert.addAction(okAction)
present(myAlert, animated:true, completion:nil)
}

}

关于Swift;将自定义 View Controller 转换到 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47079860/

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