【问题标题】:use same UIAlertController in different ViewControllers在不同的 ViewController 中使用相同的 UIAlertController
【发布时间】:2017-12-23 00:24:04
【问题描述】:

我使用了侧边导航菜单(SWReveal)。我有 4 个视图控制器。如何在不同的视图中使用相同的 alertAction。

【问题讨论】:

  • 只用它创建一个类或者用它创建一个 UIViewController 的子类可以被 4 个人共享?

标签: swift swift3 swrevealviewcontroller


【解决方案1】:
// MARK: - Alertable View

protocol AlertableView {

    // Use handler if need catch cancel alert action
    typealias CompletionHandler = (() -> Void)

    func displayAlert(with title: String, message: String, actions: [UIAlertAction]?)
    func displayAlert(with title: String, message: String, style: UIAlertControllerStyle, actions: [UIAlertAction]?, completion: CompletionHandler?)
}

extension AlertableView where Self: UIViewController {

    func displayAlert(with title: String, message: String, actions: [UIAlertAction]?) {
        self.displayAlert(with: title, message: message, style: .alert, actions: actions, completion: nil)
    }

    func displayAlert(with title: String, message: String, style: UIAlertControllerStyle, actions: [UIAlertAction]?, completion: CompletionHandler?) {

        let alertCancelAction = UIAlertAction(title: "Cancel".localized, style: .cancel) { (action) in

            guard let completion = completion else { return }
            completion()
        }

        let alertController = UIAlertController(title: title, message: message, preferredStyle: style)

        if let actions = actions {

            for action in actions {
                alertController.addAction(action)
            }

            alertController.addAction(alertCancelAction)

        } else {

            // If not any custom actions, we add OK alert button

            let alertOkAction = UIAlertAction(title: "OK".localized, style: .cancel) { (action) in

                guard let completion = completion else { return }
                completion()
            }

            alertController.addAction(alertOkAction)
        }

        self.present(alertController, animated: true, completion: nil)
    }

}

【讨论】:

    【解决方案2】:
    1. 使用可以显示警报的方法创建 BaseController

       //Copyright © 2017 dip. All rights reserved.
      
      import UIKit
      
      class BaseController: UIViewController {
      
      override func viewDidLoad() {
          super.viewDidLoad()
      
      }
      
      override func didReceiveMemoryWarning() {
          super.didReceiveMemoryWarning()
          // Dispose of any resources that can be recreated.
      }
      
      ///This is common method to show alert with same action 
      func showAlert() {
          let alert = UIAlertController(title: "Alert", message: "my msg on alert", preferredStyle: .alert)
          alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
              ///This will be common alert ok aciton for all child controllers.
              print("Do some userful common work..")
      
          }))
      
            self.present(alert, animated: true, completion: nil)            
        }
      }
      
    2. 继承您的 4 个控制器来自 BaseController

       //  Copyright © 2017 dip. All rights reserved.
      //
      
      import UIKit
      
      class ChildVC: BaseController {
      
          override func viewDidLoad() {
              super.viewDidLoad()
      
              //call show alert when ever you wish 
              ///This method will call showAlert() method on super class (BaseController)
              self.showAlert()
      
          }
         }
      
      1. 当您希望通过常见操作显示警报时,请从子级调用 self.showAlert() 方法。

    【讨论】:

    • 它不会工作,因为没有存在的方法
    【解决方案3】:

    在您的项目 swift 中,您可以创建一个新的 .swift 文件并在此文件中创建一个类:

    import UIKit
    import Foundation
    
    class yourFileName {
    
        //Create a class function alerview
        class func displayAlert(title: String, withMessage msg: String, andbtnTitle btntitle: String, in vc: UIViewController) {
            let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: btntitle, style: UIAlertActionStyle.default, handler: nil))
    
            appDelegate.window?.rootViewController?.present(alert, animated: true, completion: nil)
        }
    }
    
    //and now your any ViewController.swift file or any other file in your project you can access alert following way.
    class viewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
    
            yourfilename.displayAlert(title: "Alert", withMessage msg: "my alert view display", andbtnTitle btntitle: "Ok", in vc: self) // access your alertview
        }
    }
    

    我希望它对你有用。

    【讨论】:

      【解决方案4】:

      你也可以这样使用。

      class IOSPublicDefaultAlert: NSObject{
      
          var viewController: UIViewController?
          var actionCompletion: ((String) -> ())?
          var alertTitle: String?
          var alertMessage : String?
          var alertType: UIAlertControllerStyle?
          var actionTitleAndType: [String: UIAlertActionStyle]?
      
      
      
          init(viewController : UIViewController,alertTitle: String?,alertMessage : String?,alertType: UIAlertControllerStyle = .alert,actionTitleAndType: [String: UIAlertActionStyle] ,actionCompletion :  ((String)->())?){
      
              super.init()
              self.viewController = viewController
              self.actionCompletion = actionCompletion
              self.alertTitle = alertTitle
              self.alertMessage = alertMessage
              self.alertType = alertType
              self.actionTitleAndType = actionTitleAndType
      
              showAlert()
          }
      
      
          func showAlert(){
      
              let alert = UIAlertController.init(title: alertTitle, message: alertMessage, preferredStyle: self.alertType ?? .alert)
      
              for (actionTitle, actionType) in actionTitleAndType!{
      
                  let action = UIAlertAction(title: actionTitle, style: actionType) { (action) in
      
                      if let com = self.actionCompletion{
      
                          com(actionTitle)
                      }
                  }
                  alert.addAction(action)
              }
      
              viewController?.present(alert, animated: true, completion: nil)
          }
      }
      

      并在您喜欢的地方使用添加,如下示例所示

        _ = IOSPublicDefaultAlert.init(viewController: self, alertTitle: "Warning!!!", alertMessage: alertMessage, actionTitleAndType: ["Ok" : .destructive, "Cancel" : .default], actionCompletion: { [unowned self] (title) in
              if title == "Ok"{
      
              }
          })
      

      【讨论】:

        【解决方案5】:

        您可以创建UIViewController 扩展名,如下所示:

        extension UIViewController {
            func showAlert(title: String?, message: String?, actionTitles:[String?], actions:[((UIAlertAction) -> Void)?]) {
                    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
                    for (index, title) in actionTitles.enumerated() {
                        let action = UIAlertAction(title: title, style: .default, handler: actions[index])
                        alert.addAction(action)
                    }
                    self.present(alert, animated: true, completion: nil)
                }
            }
        

        您可以在UIViewController 中使用此警报,如下所示:

            showAlert(title: "Your Title", message: "Your custom Message", actionTitles: ["Ok","Cancel"], actions: [{ action1 in
                           //OK Action
                        }, { action2 in
                            // Cancel Action
                        }
                   ])
        

        希望能得到您的解决方案。

        【讨论】:

          【解决方案6】:

          创建一个通用函数,

          import UIKit
          
          class AlertClass: NSObject {
          
              func showAlertWithVC(_ VC : UIViewController, andMessage message: String ){
                  DispatchQueue.main.async {
                      let alert = UIAlertController(title: "APPLICATION_NAME", message: message , preferredStyle: UIAlertControllerStyle.alert)
                      alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
                      VC.present(alert, animated: true, completion: nil)
                  }
              }
          }
          

          只需在要显示警报的地方调用 AlertClass().showAlertWithVC()。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-11-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-14
            • 1970-01-01
            相关资源
            最近更新 更多