Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS TextField - autocomplete adds blank character

I have a problem with a UITextField. When I have email autocomplete option enabled, I can select an email from the list, but iOS automatically adds blank space at the end of the text field.

Is it an iOS bug or there is something I can do to prevent this? P.S. I know I can handle text changes and remove empty space from the end of the string, but I am looking for the native way.

iOS screenshot iOS screenshot

like image 324
Vladimir88dev Avatar asked Jul 09 '18 19:07

Vladimir88dev


2 Answers

The default behaviour of the smart suggestion is to add an empty space after the provided text in a way that if you're writing a sentence you would not have to hit space after picking the suggestion.

I would recommend removing the white spaces so even if the user tried to enter it then it will be discarded.

You can do that by changing the text programatically after it's changed:

Add a target to your text field in the viewDidLoad of the controller

textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

@objc func textFieldDidChange(_ textField: UITextField) {

    let text = textField.text ?? ""

    let trimmedText = text.trimmingCharacters(in: .whitespaces)

    textField.text = trimmedText
}
like image 154
zombie Avatar answered Nov 05 '22 03:11

zombie


Any text selected from the QuickType bar appends a space, I guess it's to avoid having to manually add a space every time. I imagine expecting iOS to smartly not add that space goes against that convenience. At least the space is automatically removed if you add a period.

I solve this by creating a subclass of UITextField all application textfields:

import UIKit

class ApplicationTextField: UITextField {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        NotificationCenter.default.addObserver(self, selector: #selector(didEndEditing(notification:)), name: UITextField.textDidEndEditingNotification, object: nil)
    }

    @objc private func didEndEditing(notification:Notification) {
        self.text = self.text?.trimmingCharacters(in: .whitespaces)
    }
}

To allow other object to implement the UITextFieldDelegate, I use the NotificationCenter and observe the didEndEditing(notification:) notification.

like image 2
dev_exo Avatar answered Nov 05 '22 05:11

dev_exo