在Swift 3中,我需要检测用户是否在UITextField之外触摸,然后检查特定的UITextField是否是发件人,然后保存文本。我一直在尝试使用Notification Center进行此操作我在Swift 2中找到了示例,但我很难为Swift 3实现正确的语法。
let notificationName = Notification.Name("UITextFieldTextDidChange")
NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldDidChange), name: notificationName, object: nil)
NotificationCenter.default.post(name: notificationName, object: nil)
func textFieldDidChange(sender: AnyObject) {
if let notification = sender as? NSNotification,
let textFieldChanged = notification.object as? UITextField
where textFieldChanged == self.myTextField {
storedText = myTextField.text!
}
}
我发现这种做法略有不同,对我有用:
myTextField.addTarget(self, action: #selector(didChangeText(textField:)), for: .editingChanged)
func didChangeText(textField: UITextField) {
if let textInField = myTextField.text {
myTextField.text = textInField
storedText = myTextField.text!
}
}