gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:02:15 24 4
gpt4 key购买 nike

我正在尝试更多地了解 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)
}

现在我要做的是替换 continueAction 的处理程序 UIAlertAction使用我从外部收到的处理程序,它将从序列号 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
}

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

Cannot convert value of type '(UIAlertAction) -> String?' to expected argument type '((UIAlertAction) -> Void)?'



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

最佳答案

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

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)")
}

关于ios - 有没有办法将一个闭包传递给 UIAlertAction,它会在 Swift 中返回一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48971330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com