【问题标题】:create alert function in all view controllers - swift在所有视图控制器中创建警报功能 - swift
【发布时间】:2017-04-12 08:08:23
【问题描述】:

我正在尝试声明一个用于在我的应用中显示警报的函数。为避免重复工作,我尝试对我的所有应用程序使用相同的功能。我试图通过创建一个带有函数 showNotification 的类来做到这一点。但是当我创建该类的对象并调用该方法时,什么也没有发生。我该怎么做?

class SharedPropertiesAndMetods : UIViewController {

    func showNotification(title: String, message: String)
    {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "تائید", style: .default, handler: nil)
        alertController.addAction(defaultAction)
        present(alertController, animated: true, completion: nil)
    }

}

【问题讨论】:

  • 将此方法添加为 UIViewController 的扩展
  • @HosAp 有 4 个答案。它们都没有帮助吗?
  • @GaneshKumar 是的,添加为扩展是个好主意
  • @GaneshKumar 是的,抱歉我没有注意到。如果您同意,卢卡的回答会更全面。感谢您的帮助

标签: ios swift uiviewcontroller uialertview uialertcontroller


【解决方案1】:

使用这样的扩展

extension UIViewController {
  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)
  }
}

这样调用函数

self.showAlert(title: "hi", message: "test")

【讨论】:

    【解决方案2】:

    我要做的是创建一个“通用”视图控制器来完成这项工作,而不是从它继承:

    1.如果您想在每次视图确实出现时显示警报:

    class GenericViewController: UIViewController {
    
        // MARK: - View lifecycle -
    
        override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
            if let notification = self.shouldDisplayAlertNotification() {
                self.showNotification(notification)
            }
        }
    
        // MARK: - Internal methods -
    
        func shouldDisplayAlertNotification() -> AlertNotification? {
            return nil
        }
    
        // MARK: - Private methods -
    
        private func showNotification(_ alertNotification: AlertNotification) {
        }
    
    }
    
    class MyController: GenericViewController {
    
        override func shouldDisplayAlertNotification() -> AlertNotification? {
            return AlertNotification(title: "Title", message: "Message")
        }
    
    }
    

    AlertNotification 是您的自定义模型类:

    class AlertNotification {
        var title: String
        var message: String
    
        init(title: String, message: String) {
            self.title = title
            self.message = message
        }
    }
    

    这样,只有覆盖shouldDisplayAlertNotification的VC才会显示警报。

    2。如果您想在“需求”时显示警报:

    按照建议,扩展 UIViewController

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

    【讨论】:

    • 这样,当我想在我的 VC 中使用 viewDidAppear 时,它会覆盖 GenericViewContoller 的 viewDidAppear。不是吗?
    • 是的,但是你可以调用 super.viewDidAppear 作为第一条指令,所以会显示警报
    【解决方案3】:

    其实你可以在类之外的任何地方声明一个简单的方法。

    func showAlertWithCompletion(message:String,okTitle:String,cancelTitle:String?,completionBlock:@escaping (_ okPressed:Bool)->()){
        let alertController = UIAlertController(title: AppName, message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: okTitle, style: .default) { (ok) in
            completionBlock(true)
        }
        alertController.addAction(okAction)
        if let cancelTitle = cancelTitle{
            let cancelOption = UIAlertAction(title: cancelTitle, style: .cancel, handler: { (axn) in
                completionBlock(false)
    
            })
            alertController.addAction(cancelOption)
        }
    
        if let topController = UIWindow.topViewController(){
          topController.present(alertController, animated: true, completion: nil)
        }
    
    }
    

    这样,无论您调用它,您都会在完成句柄中获得 ok 按钮按下回调,甚至按照@Ganesh Kumar 的描述进行扩展

    【讨论】:

      【解决方案4】:

      为什么不只是一个扩展

      extension UIViewController {
      
          func showNotification(title: String, message: String)
          {
              let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
              let defaultAction = UIAlertAction(title: "تائید", style: .default, handler: nil)
              alertController.addAction(defaultAction)
              present(alertController, animated: true, completion: nil)
          }
      }
      

      【讨论】:

        【解决方案5】:

        您可以使用此视图控制器扩展在整个应用程序中呈现警报视图。 https://github.com/SumitKr88/UIViewController-ShowAlertView/blob/master/UIViewController%2BExtensions.swift

        extension UIViewController {
        
        /// Show alert view
        /// - Parameter title: title of alert
        /// - Parameter message: message of alert
        /// - Parameter actionTitles: List of action button titles(ex : "OK","Cancel" etc)
        /// - Parameter style: Style of the buttons
        /// - Parameter actions: actions repective to each actionTitles
        /// - Parameter preferredActionIndex: Index of the button that need to be shown in bold. If nil is passed then it takes cancel as default button.
        
        /**
         Example usage:-
         Just make sure actionTitles and actions array the same count.
        
         /********** 1. Pass nil if you don't need any action handler closure. **************/
         self.showAlert(title: "Title", message: "message", actionTitles: ["OK"], style: [.deafult], actions: [nil])
        
         /*********** 2. Alert view with one action **************/
        
         ///     let okActionHandler: ((UIAlertAction) -> Void) = {(action) in
         //Perform action of Ok here
         }
         self.showAlert(title: "Title", message: "message", actionTitles: ["OK", "CANCEL"], style: [.default, .cancel], actions: [okayActionHandler, nil])
        
         /********** 3.Alert view with two actions **************/
        
         let okActionHandler: ((UIAlertAction) -> Void) = {(action) in
         //Perform action of ok here
         }
        
         let cancelActionHandler: ((UIAlertAction) -> Void) = {(action) in
         //Perform action of cancel here
         }
        
         self.showAlert(title: "Title", message: "message", actionTitles: ["OK", "CANCEL"], style: [.default, .cancel], actions: [okActionHandler,cancelActionHandler], preferredActionIndex: 1)
         */
        
        public func showAlert(title: String?,
                              message: String?,
                              actionTitles: [String?],
                              style: [UIAlertAction.Style],
                              actions: [((UIAlertAction) -> Void)?],
                              preferredActionIndex: Int? = nil) {
            let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
            for (index, title) in actionTitles.enumerated() {
                let action = UIAlertAction(title: title, style: style[index], handler: actions[index])
                alert.addAction(action)
            }
            if let preferredActionIndex = preferredActionIndex { alert.preferredAction = alert.actions[preferredActionIndex] }
            self.present(alert, animated: true, completion: nil)
        }}
        

        【讨论】:

          【解决方案6】:

          您可以为 alertController 创建扩展,还可以选择操作处理程序。这将允许根据是否需要处理程序使用两个不同的警报控制器。

          extension  UIAlertControler {
          
          class func genericErrorAlert(forAlert message: String, completion: ((UIAlertAction) -> Void)? = nil )
          
              let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
          
              alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: completion))
          
              return alert
            }
          }
          

          【讨论】:

            【解决方案7】:

            您还可以在您的应用中创建一个 util 文件,因为您可以添加任何可重用的方法或函数并在您的应用中的任何位置使用它,

            导入基础 导入 UIKit

            //标记:-警报

            func showMessage(title: String, message: String!, VC: UIViewController) {

            let alert : UIAlertController = UIAlertController(title: "", message: message, preferredStyle: UIAlertControllerStyle.alert)
            let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
                UIAlertAction in
            }
            alert.addAction(okAction)
            VC.present(alert, animated: true, completion: nil)
            

            }

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多