Swift 3 - Saving text when user touches outside UITextField

In Swift 3, I need to determine if the user is touching outside of a UITextField, and then check that the specific UITextField is the sender, and then save the text. I tried to do this using the Notification Center. I found examples in Swift 2, but I try to implement the correct syntax for 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!
        }
    }

UPDATE

I found a slightly different way to do this, which works for me:

    myTextField.addTarget(self, action: #selector(didChangeText(textField:)), for: .editingChanged)

    func didChangeText(textField: UITextField) {
        if let textInField = myTextField.text {
            myTextField.text = textInField
            storedText = myTextField.text!
        }
    }
+4
source share

Source: https://habr.com/ru/post/1653516/


All Articles