Swift 4.0 iOS 11.x
添加了一些UITextfields,成为第一个响应者而不是这些观察者。但他们似乎永远不会开火?我在这里缺少什么?
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var hintTextField: UITextField!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
listenToTextFields()
}
private func listenToTextFields() {
let center = NotificationCenter.default
let queue = OperationQueue.main
namedObserver = center.addObserver(forName: NSNotification.Name.UITextViewTextDidChange, object: nameTextField, queue: queue) { (notification) in
print("You edited \(self.nameTextField.text)")
}
hintObserver = center.addObserver(forName: NSNotification.Name.UITextViewTextDidChange, object: hintTextField, queue: queue) { (notification) in
print("You edited \(self.hintTextField.text)")
}
}
当我在nameTextField或hintTextField中输入文本时,没有任何内容打印到控制台。尝试使类成为UITextFieldDelegate,并确实设置了textfield委托,但仍然没有通知我的方式?
答案 0 :(得分:1)
答案 1 :(得分:0)
好的,通过使用不同的通知让它工作似乎;但肯定不会这样做。
private func listenToTextFields() {
let center = NotificationCenter.default
let queue = OperationQueue.main
let alert2Monitor = NSNotification.Name.UITextFieldTextDidEndEditing
namedObserver = center.addObserver(forName: alert2Monitor, object: nameTextField, queue: queue) { (notification) in
self.setWayPoint.didSetVariable(image: nil, name: self.nameTextField.text, hint: self.hintTextField.text)
}
hintObserver = center.addObserver(forName: alert2Monitor, object: hintTextField, queue: queue) { (notification) in
self.setWayPoint.didSetVariable(image: nil, name: self.nameTextField.text, hint: self.hintTextField.text)
}
}