Passing functions as parameters in Swift

前端 未结 4 1900
暖寄归人
暖寄归人 2021-02-05 00:17

I have the following function working as I expect, in iOS 8:

func showConfirmBox(msg:String, title:String,
    firstBtnStr:String,
    secondBtnStr:String,
    c         


        
4条回答
  •  忘了有多久
    2021-02-05 00:37

    Adding to got2jam's answer... If you're working with UIAlertController

    The generic function to show an alert with closure:

    func showAlertAction(title: String, message: String, actionClosure: @escaping () -> Void){
      let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
      alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: {(action: UIAlertAction!) in actionClosure()}))
      self.present(alertController, animated: true, completion: nil)
    }
    

    Now you can call it like that:

    showAlertAction(title: "This is the title", message: "This is the message") {
       self.close()
    }
    

    in this case, close is the particular UIAlertAction to execute

    func close(){
      dismiss(animated: true, completion: nil)
    }
    

提交回复
热议问题