如何解决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
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。