4

so here's my problem. I'm using UITextField for payment card number and I'm formatting this number on .editingChanged so that it always has format of 4 digits with space between them. (Example: 5213 0000 0000 1234).

The problem is that when I copy-paste the (unformatted) number from sms for example, the cursor will occur after the 16th character (Example: 5213 0000 0000 1|234).

I need the cursor to be at the end, but so far nothing works for me. I tried setting the position after the formatting in the same func that's fired on .editingChanged (I used this answer as tutorial), but nothing really happend.

I also tried to make my custom UITextField where I overrided the closestPosition func so that cursor will be always at the end and user couln't move it, but even after that cursor appears at the 16th position after copy-paste.

Does anybody know how to deal with this? Thanks for all the help. <3

(note: We are supporting only 16 digits card numbers)

1 Answers1

9

You can update the cursor position using the selectedTextRange property of the textfield (which is part of the UITextInput protocol that it adopts).

Update that property after you've modified the textfield's text property:

// Add spaces as required here then:

DispatchQueue.main.async {
    let end = self.textField.endOfDocument
    let range = self.textField.textRange(from: end, to: end)
    self.textField.selectedTextRange = range
}

Note: you usually have to schedule that to be done on the next run loop if you've modified the textfield's text string immediately before (hence the use of the main DispatchQueue). Not sure why that is, but it’s possibly a UIKit bug.

The UITextInput documentation can be found here (always a good place to start looking if you want to do something with a textfield beyond accessing its text):

https://developer.apple.com/documentation/uikit/uitextinput

Pete Morris
  • 1,472
  • 8
  • 13