gpt4 book ai didi

ios - 将文本从 UIAlertController 返回到扩展中

转载 作者:搜寻专家 更新时间:2023-11-01 06:11:34 25 4
gpt4 key购买 nike

在 Swift 中,如果此 UIAlertController 在扩展中,我如何返回我写入 UIAlertController 文本字段的字符串

通常,如果您将 UIAlertController 实现放在您的本地类中,您可以轻松传递文本,但是当警报进入扩展时,我不确定返回文本的方式。

例如,假设您有这个扩展:

extension UIViewController {
func presentTextFieldAlert(title: String, message: String, textFieldPlaceholder: String ) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let saveAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default) { _ -> Void in
let urlTextField = alertController.textFields![0] as UITextField
if urlTextField.text != nil { }
}

let cancelAction = UIAlertAction(title: "Cancel", style: .default)
alertController.addTextField { (textField: UITextField!) -> Void in
textField.placeholder = textFieldPlaceholder
}
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}

进入你的类(class):

class Client: UIViewController {

func showAlert() {
self.presentTextFieldAlert(title: "Hello", message: "Write sth", textFieldPlaceholder: "Write here")
}
}

如何将文本从警报传递到 View Controller ?

我试过类似的方法:

class Client: UIViewController {

func showAlert() -> String {
return self.presentTextFieldAlert(title: "Hello", message: "Write sth", textFieldPlaceholder: "Write here")
}
}

但我认为这不是正确的方法。

最佳答案

使用完成处理程序。

extension UIViewController {
func presentTextFieldAlert(title: String, message: String, textFieldPlaceholder: String, completion: @escaping (String?)->()) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let saveAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default) { _ -> Void in
let urlTextField = alertController.textFields![0] as UITextField
completion(urlTextField.text)
}

let cancelAction = UIAlertAction(title: "Cancel", style: .default)
alertController.addTextField { (textField: UITextField!) -> Void in
textField.placeholder = textFieldPlaceholder
completion(nil)
}
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}

然后您可以将其用作:

class Client: UIViewController {

func showAlert() {
self.presentTextFieldAlert(title: "Hello", message: "Write sth", textFieldPlaceholder: "Write here") { (result) in
if let result = result {
// User entered some text and tapped OK.
}
}
}
}

关于ios - 将文本从 UIAlertController 返回到扩展中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55642026/

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