具有这样的警报功能:
var completionHandlers: [() -> Void] = []
func alert(header: String,
message: String,
okButton: String,
completionHandler: @escaping () -> Void) {
let alert: UIAlertController = UIAlertController.init(title: header,
message: message,
preferredStyle: UIAlertControllerStyle.alert)
let ok: UIAlertAction = UIAlertAction.init(title: okButton,
style: UIAlertActionStyle.default) { (_) in
alert.dismiss(animated: true, completion: {
self.completionHandlers.append(completionHandler)
})
}
alert.addAction(ok)
self.present(alert, animated: true)
}
这里是这个函数的用法:
self.alert(header: "Warning", message: "The date of end must be selected", okButton: "Ок", completionHandler: {
print("test")
})
所以问题是,我的completionHandler根本不起作用。即使测试也没有在控制台中打印。那么如何用闭包来纠正 make handler 呢?
最佳答案
您实际上从未调用传递给 alert
的完成处理程序。您所做的就是将其添加到数组中。
不需要 completionHandlers
数组(至少在您发布的代码中不需要)。并且您不需要在警报操作中关闭警报。
将警报操作更改为:
let ok: UIAlertAction = UIAlertAction.init(title: okButton, style: .default) { (_) in
completionHandler()
}
关于swift - CompletionHandler 不适用于 UIAlertController 中的闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44570126/