如何解决无法在 swift 的范围错误中找到“UIAlertController”?
如果我在单独的 swift 文件中编写警报函数,或者如果我使用扩展名,它不会出现在另一个视图控制器中,为什么会出现 Cannot find 'UIAlertController' in scope?
错误?
代码:
func showAlert(title: String,message: String) {
let alertController = UIAlertController(title: title,message:
message,preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK",style: .default,handler: {action in
}))
self.present(alertController,animated: true,completion: nil)
}
错误:
在范围内找不到“UIAlertController”,
在范围内找不到“UIAlertAction”
在范围内找不到“自我”
解决方法
可能你在 viewController 中忘记了这一点:
import UIKit
所以你的文件不知道 UIAlertController
或 UIAlertAction
是什么
如果你想创建一个在多个 UIViewController 中使用的警报视图控制器,你可以这样做:
import UIKit
class CustomAlertController: NSObject {
let message:String?
let title:String?
init(title:String,message:String) {
self.message = message
self.title = title
}
func showAlert()->UIAlertController {
let alertController = UIAlertController(title: self.title,message: self.message,preferredStyle: .alert)
// you can further customize your buttons,buttons' title etc
alertController.addAction(UIAlertAction(title: "OK",style: .default,handler: {action in
}))
return alertController
}
}
然后是你的视图控制器
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let alert = CustomAlertController(title: "Hello",message: "My message to the world")
DispatchQueue.main.async {
self.present(alert.showAlert(),animated: true,completion: nil)
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。