【问题标题】:makeAlert Function Returns Always FalsemakeAlert 函数总是返回 False
【发布时间】:2021-01-03 09:41:19
【问题描述】:

下面的函数总是返回 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

}

【问题讨论】:

    标签: swift alert uialertview swift5


    【解决方案1】:

    你必须像这样使用完成。

    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
    }
    

    【讨论】:

    • 感谢您的回复。当我使用 FSCalendar 时,我想在该函数完成后返回布尔值。请看截图。 drive.google.com/file/d/129sYjKDhJPNOYXZOjAAKSWssZWBTlq3W/… 它仍然无法按我需要的方式工作。
    • @EvrimDemir 然后请在您的问题中添加这一点,以便用户给出适当的答案。检查我更新的答案。
    • Raja,很好,它按预期工作。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    相关资源
    最近更新 更多