iOS TextField - autocomplete adds blank character iOS TextField - autocomplete adds blank character ios ios

iOS TextField - autocomplete adds blank character

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}

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 UIKitclass 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.

I haven't found the way to solve this problem. Honestly, I haven't spent a lot of time. I am still working on a project, so I have left this problem on standby because I am working on other features. We can consider this as an Apple bug. Btw, the email text field offers a way for entering blank space, I don't know why since email addresses don't contain blank characters. For now, I have an idea to overcome this problem by fixing email address after editing, not during editing.

For example, I can accept this email with a blank character as input from autocomplete, but when I save that email or send email to that address, I could remove the blank space.