UIViewcontroller和UITableviewcontroller Swift的通用协议

时间:2019-04-10 07:29:30

标签: ios swift uitableview uiviewcontroller

我正在编写一些常用方法来显示警报加载程序之类的东西,

我希望可以从uiviewcontroller和uitableviewcontroller子类访问这些方法,

我们怎么能达到相同的目标?

4 个答案:

答案 0 :(得分:2)

UITableViewControllerUIViewController的子类,您可以创建UIViewController的扩展,并且声明的函数可以被这两个实例访问:

extension UIViewController {
    func showAlert(title: String, message: String) {
        ...
    }
}

答案 1 :(得分:2)

创建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方法。

答案 2 :(得分:1)

创建NSObject类型的通用文件,请参见以下代码。然后您可以从UIViewControllerUITableviewController或任何文件/控制器中调用。

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")

答案 3 :(得分:1)

您可以通过以下方式编写全局方法:

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")