makeAlert 函数总是返回 False

问题描述

下面的函数总是返回false。我试图将 return 放在它也不接受的完成中。

你能帮我吗?

// MARK: - make Alert for user Input
func makeAlert(message: String,defaultButtonText: String,cancelButtonText: String) - > Bool {

  var answer = Bool()

  let alert = UIAlertController(title: "Warning",message: message,preferredStyle: .alert)

  let actionYes = UIAlertAction(title: defaultButtonText,style: .default) {
    (action) in

    answer = true

  }

  let actionNo = UIAlertAction(title: cancelButtonText,style: .default) {
    (action) in
    answer = false

  }
  alert.addAction(actionNo)
  alert.addAction(actionYes)
  self.present(alert,animated: true,completion: {
    print(answer)
  })


  return answer

}

解决方法

你必须像这样使用补全。

func makeAlert(message: String,defaultButtonText: String,cancelButtonText: String,completion: @escaping ((Bool) -> Void)) {
    
    let alert = UIAlertController(title: "Warning",message: message,preferredStyle: .alert)
    
    let actionYes = UIAlertAction(title: defaultButtonText,style: .default) { (action) in
        completion(true)
    }
    
    let actionNo = UIAlertAction(title: cancelButtonText,style: .default) { (action) in
        completion(false)
    }
    alert.addAction(actionNo)
    alert.addAction(actionYes)

    self.present(alert,animated: true,completion: {

    })
}

用法:

makeAlert(message: "Test",defaultButtonText: "Test",cancelButtonText: "Test") { (action) in
    if action {
        // Do code for true part
    } else {
        // Do code for false part
    }
}

编辑

根据commnet。如何在 FSCalendar 中使用

func calendar(_ calendar: FSCalendar,shouldSelect date: Date,at monthPosition: FSCalendarMonthPosition) -> Bool {
    makeAlert(message: "Test",defaultButtonText: "Yeah",cancelButtonText: "No") { (action) in
        if action {
            calendar.select(date)
        }
    }
    return false
}