Ric*_*dro 1 ios swift uialertcontroller
在 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)
}
}
Run Code Online (Sandbox Code Playgroud)
进入你的课堂:
class Client: UIViewController {
func showAlert() {
self.presentTextFieldAlert(title: "Hello", message: "Write sth", textFieldPlaceholder: "Write here")
}
}
Run Code Online (Sandbox Code Playgroud)
如何将警报中的文本传递给视图控制器?
我试过这样的事情:
class Client: UIViewController {
func showAlert() -> String {
return self.presentTextFieldAlert(title: "Hello", message: "Write sth", textFieldPlaceholder: "Write here")
}
}
Run Code Online (Sandbox Code Playgroud)
但我认为这不是正确的方法。
使用完成处理程序。
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)
}
}
Run Code Online (Sandbox Code Playgroud)
然后您可以将其用作:
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.
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
245 次 |
| 最近记录: |