【发布时间】:2019-08-31 14:03:50
【问题描述】:
我正在编写一些常用方法来显示警报加载器之类的东西,
我希望从 uiviewcontroller 和 uitableviewcontroller 子类访问这些方法,
我们怎样才能达到同样的效果?
【问题讨论】:
标签: ios swift uitableview uiviewcontroller
我正在编写一些常用方法来显示警报加载器之类的东西,
我希望从 uiviewcontroller 和 uitableviewcontroller 子类访问这些方法,
我们怎样才能达到同样的效果?
【问题讨论】:
标签: ios swift uitableview uiviewcontroller
创建UIViewController 扩展并添加您的警报方法,如下所示。
extension UIViewController {
func showAlert(title: String, message: String, buttonName: String, alertActionHandler: ((UIAlertAction) -> Void)? = nil) {
guard let alertActionHandler = alertActionHandler else {
return
}
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let actionButton = UIAlertAction(title: buttonName, style: .default, handler: { action in
alertController.dismiss(animated: true, completion: nil)
alertActionHandler(action)
})
alertController.addAction(actionButton)
self.present(alertController, animated: true, completion: nil)
}
}
您可以在视图控制器的任何位置调用showAlert 方法。
【讨论】:
UITableViewController 是UIViewController 的子类,您可以创建UIViewController 的扩展,并且其中声明的函数可以被两者的实例访问:
extension UIViewController {
func showAlert(title: String, message: String) {
...
}
}
【讨论】:
创建 NSObject 类型的通用文件,如下代码。然后您可以从UIViewController 或UITableviewController 或任何文件/控制器调用。
import UIKit
class AppUtils: NSObject {
static func showAlert(title: String, message: String) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let ok = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(ok)
UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
}
}
}
调用showAlert函数:-
AppUtils.showAlert(title: "My Title", message: "My Message")
【讨论】:
AppUtils 需要是NSObject 的子类?这完全没有必要……
UIView 提供它。此外,让你的类从NSObject 继承并不会改变它的可见性,你可以在没有继承的情况下实现同样的效果。
你可以这样写一个全局方法:
func showAlert(_ view: UIView, title: String, message: String) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
switch action.style{
case .default:
print("default")
case .cancel:
print("cancel")
case .destructive:
print("destructive")
}}))
view.present(alert, animated: true, completion: nil)
}
}
并在每个 ViewController 中使用它:
showAlert(self.view, title: Alert, message: "Hi")
【讨论】:
UIViewController,不需要声明一个全局函数。