How to add alert message to a global class

后端 未结 5 1240
刺人心
刺人心 2021-01-26 09:29

I have the following code repeated in many of my view controllers. I would like to refactor it into a global class/view controller. However, I still want it to be s

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-26 10:18

    Swift 4.0

    You can use action closure for multiple actions.

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

    And you can use like this in UIViewController

     popupAlert(title: kTitle, message: "This is test alert!!!!" , actionTitles: ["Ok","Cancel"], actions: [ { action1 in
                //perform action for OK button
                }, { action2 in
               //perform action for cancel button
      }])
    

提交回复
热议问题