我有一个带有 textField
的 UIAlertController
。由于我无法为 textField
创建导出,因此我必须找到另一种方法来获得实时观察用户输入的功能。
我做了一些尝试,但没有成功。该线程解释了如何将目标添加到文本字段:
How do I check when a UITextField changes?
textfield.addTarget(self, action: #selector(ViewControllerr.textFieldDidChange(_:)), for: UIControl.Event.editingChanged)
我试过了,但不太理解 #selector
输入。它需要我的 UIViewController?
还是我的 UIAlertController
我都试过了,但得到了相同的错误消息:
“UIViewController”类型的值没有成员“textFieldDidChange”
与 UIAlertController
相同。
我还尝试将我的 textField
设置为委托(delegate)访问该类的函数:
textField.delegate = self as? UITextFieldDelegate
但我想这不是正确的方法,因为我仍然无法访问任何功能,除非这样做:
textField.delegate?.textFieldDidBeginEditing?(textField)
但这也没有给我任何东西。
我也试过添加这样的扩展:
extension UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
print("🦋EDITING")
}// became first responder
func textFieldDidEndEditing(_ textField: UITextField) {
print("🦋EDITING")
}
}
但由于某些原因我无法通过 textView
访问它们
如果我这样扩展类:
extension PickNumberViewController: UITextFieldDelegate {...}
同样的错误信息
Value of type 'UITextField' has no member 'textFieldDel...'
这没有意义,因为我将 textField
设置为 UITextFieldDelegate
而不是 UITextField
。
如果您也想查看我的代码,请告诉我。
最佳答案
您可以尝试使用 self.text = alert.text Fields?[0]
class ViewController: UIViewController {
var textF:UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
//1. Create the alert controller.
let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)
alert.addTextField { (textField) in
textField.text = "Some default text"
}
let tex = alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
}))
// 4. Present the alert.
self.present(alert, animated: true, completion: nil)
self.textF = alert.textFields?[0]
self.textF.addTarget(self, action: #selector(self.textFieldDidChange), for: UIControl.Event.editingChanged)
}
}
@objc func textFieldDidChange() {
print(textF.text)
}
}
关于swift - 如何观察用户在 UIAlertController 中编辑文本字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58182601/