24

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

shim
  • 7,170
  • 10
  • 62
  • 95
iOSDev
  • 653
  • 1
  • 8
  • 18

5 Answers5

13

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
}
zombie
  • 4,242
  • 2
  • 19
  • 48
  • or you can use the delegate – Nicholas Jul 10 '18 at 09:59
  • Thanx for the answers, but I know how to remove empty space. I just want to know if there is a native way for eliminating white space at the end of suggested string – iOSDev Jul 10 '18 at 14:03
  • @VladimirDinic did you ever find a way? I came across this problem recently, and was wondering if there was some kind of flag I should've been setting (or not setting). – Dan Morrow Sep 16 '18 at 14:12
  • @DanMorrow, unfortunately, no, but I have an idea to solve this problem by handling this empty space after editing (on saving, on sending email), not during editing. – iOSDev Sep 16 '18 at 23:43
  • @Edward the delegates don't fire for me when Autofill applies the values. – jlmurph Nov 28 '18 at 23:36
  • @jlmurph Have you set the delegate on the relevant textfield? `textField(shouldChangeCharactersIn:replacementString:)` works for me. – idrougge Mar 22 '19 at 08:54
  • haven't looked at this in a while, but will try again and update – jlmurph Apr 04 '19 at 13:15
  • The problem with this method is it will prevent typing any spaces in the field (unless that's what you want). If that's not what you want, then this could be useful: https://stackoverflow.com/questions/46391814/how-to-detect-when-user-used-password-autofill-on-a-uitextfield – Drew Jul 19 '19 at 16:57
  • delegate does not work for me too, but target works good – Matrosov Alexander Apr 06 '21 at 12:36
2

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.

dev_exo
  • 134
  • 1
  • 8
-1

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.

iOSDev
  • 653
  • 1
  • 8
  • 18
-5

If you googled this and you are using React Native, then you will need to .trim() your value when you save it and verify it.

e.g. if you render your email TextInput field:

     <TextInput
            ref={(input) => {
              this.emailTextInput = input;
            }}
            clearButtonMode={'while-editing'}
            autoComplete={"email"}
            textContentType={"emailAddress"}
            keyboardType={"email-address"}
            placeholder={"Email"}
            maxLength={100}
            onChangeText={email => this.validateAndSet("email", email)}
          />

and then in your onChange/Validation function make sure you trim the the value:

  validateAndSet(key, value) {

    // do validations, mark fields as invalid, etc.

    this.setState({ [key]: value });

    if (key === 'email') {
      this.setState({email: value.trim()})
    }
  }
Toshe
  • 728
  • 4
  • 15
-5

i worked around it on react-native with redux-form by checking props.textContentType == "emailAddress" as below:

 <TextInput

            {...props}
            onChangeText={props.input.onChange}
            value={props.textContentType == "emailAddress"? props.input.value.trim(): props.input.value}
        />