有没有办法将闭包传递给 UIAlertAction,这将在 Swift 中返回一个字符串?



我正在尝试更多地了解 Swift Closure 概念,但我有这个问题,我有以下 UIAlertController 方法:

public static func showSerialNumberAlertController(handler: @escaping (UIAlertAction) -> String?) {
let alertController = UIAlertController(title: "Serial Number", message: "Please enter your serial number", preferredStyle: .alert)
// ADD ACTIONS HANDLER
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
cancelAction.isEnabled = true
alertController.addAction(cancelAction)
let continueAction = UIAlertAction(title: "Continue", style: .default) { (_) in
let serialNumberField = alertController.textFields![0] as UITextField
let text = serialNumberField.text
print("Serial number entered: (text!)")
}
continueAction.isEnabled = false
alertController.addAction(continueAction)
// ADD TEXT FIELDS
alertController.addTextField { (textField) in
textField.placeholder = "Serial number"
// enable continue button when serial not empty
NotificationCenter.default.addObserver(forName: NSNotification.Name.UITextFieldTextDidChange, object: textField, queue: OperationQueue.main) { (notification) in
continueAction.isEnabled = textField.text != "" && textField.text?.count as! Int > 3
}
}
alertController.view.tintColor = Colors.mainColor
getRootViewController()?.present(alertController, animated: true)
}

现在我要做的是用我从外部收到的处理程序替换continueActionUIAlertAction的处理程序,当用户按下继续按钮并将其作为返回值传递时,该处理程序将从序列号中提取文本UITextField

所以我在另一个文件中有这个范围之外的这个方法,我从中调用这个静态方法:

public func getSerialFromAlert(alertController: UIAlertController) -> String? 
{
let serialNumberField = alertController.textFields![0] as UITextField
let text = serialNumberField.text
print("Serial number entered: (text!)")
return text
}

我想将此方法作为处理程序传递,但是当我这样做时,我收到此错误:

无法将类型"(UIAlertAction)-> String?"的值转换为预期的参数类型"((UIAlertAction)-> Void)?

所以问题是:是否有可能实现这一点并传递一个将返回值作为参数的处理程序?如果是这样,正确的方法是什么?如果不是,对于必须访问警报视图才能提取数据的UIAlertController操作委托,将采取什么替代方法?

如果我理解正确,您可以将方法签名更改为

showSerialNumberAlertController(completion: @escaping (String) -> Void)

在此函数中,将继续操作更改为:

let continueAction = UIAlertAction(title: "Continue", style: .default) { (_) in
let serialNumberField = alertController.textFields![0] as UITextField
let text = serialNumberField.text
completion(text ?? "")
}

最后,你像这样调用该方法:

UIAlertController.showSerialNumberAlertController { serial in
print("Serial number entered: (serial)")
}

最新更新