1

If I copy abc 123, and paste it into my UITextField, I’d like abc123 to be entered. I’m trying to use shouldChangeCharactersInRange:replacementString from UITextFieldDelegate, but changing the replacementString argument doesn’t change what actually appears in the field.

I can return NO if the string contains spaces, but what I’d like to do is actually strip them at the point of entry. There doesn’t appear to be any other delegate method to do this.

How might I achieve this, preferably without subclassing the UITextField and overriding paste:?

Luke
  • 9,512
  • 15
  • 82
  • 146

3 Answers3

2

You can observe UIPasteBoard for changes and change the string before paste:

[[NSNotificationCenter defaultCenter]
   addObserver:self
   selector:@selector(pasteboardChangedNotification:)

Once you get the notification you can then get the string and replace spaces.

NSString *newString = [[[UIPasteboard generalPasteboard] string] stringByReplacingOccuranciesOfString:@" " withSting:@""]

Nikos M.
  • 13,685
  • 4
  • 47
  • 61
  • This won’t work if the text isn’t copied from my app. I’m actually stripping spaces from a copied new password in an email or Safari, wanting to strip spaces that may have been picked up when the customer highlights the text in the browser. – Luke Mar 21 '15 at 13:08
0

You need to strip the spaces out of replacementString and then set the text property of the UITextField to the modified replacementString and return NO (because you have already done it manually).

jakedunc
  • 984
  • 9
  • 20
0

I could achieve this behavior overriding textField:shouldChangeCharactersInRange:replacementString: making the changes inside the method to the textField (set the text to the formatted version) and returning NO.

Dario
  • 3,105
  • 1
  • 17
  • 16