Swift 3 - 当用户触摸UITextField之外时保存文本

时间:2016-09-03 11:30:01

标签: uitextfield nsnotificationcenter swift3 notificationcenter

在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!
        }
    }

0 个答案:

没有答案