Before I get asked, no this is not a duplicate. No other question addresses this that I found with a satisfying answer.
I have been working on some code to make a data interface and I didn’t want to use a date picker.
This is the code I’m using to get the XX/XX/XX format:
extension OneCreateAccountViewController {
func textFieldDidChangeSelection(_ textField: UITextField) {
if textField.placeholder == "DD/MM/YY" {
if textField.text!.count >= 2 && textField.text!.count < 3 {
textField.text! = "(textField.text!)/"
} else {
if textField.text!.count >= 5 && textField.text!.count < 6 {
textField.text! = "(textField.text!)/"
} else {
if textField.text!.count >= 9 {
textField.text!.removeLast()
}
}
}
}
}
}
As you can see it is pretty barebones, but my issue is that once "/" is inserted, no matter what happens, you cannot remove using the return key. I want a specific else statement that would work something like "else – if the backspace is returned and the last character is "", delete that character."
please help me in SPECIFICALLY HAVING A CODE THAT REGISTERS THE RETURN KEY (even if it is a simple "if return is pressed, print ("Hi")" like answer.)
2
Answers
Use below.
You will have a lot of trouble trying to do this with only
textFieldDidChangeSelection
…To answer your specific "CODE THAT REGISTERS THE RETURN KEY" question, implement
textFieldShouldReturn
in yourUITextFieldDelegate
:To detect Backspace, implement
shouldChangeCharactersIn
:Important note!! – that will fail due to a bug in the iOS simulators! It does work on an
iOS 15.0
simulator, and I’ve seen notes that the bug is fixed in `iOSFor the simplest approach, handle each new input in
shouldChangeCharactersIn
:Your task will be, however, rather more complex…
For example, suppose the user has typed
25/12/2
and moves the caret / insertion point:What should happen if a
0
is typed? Or a backspace? Do you want to insert/delete where the caret is, reformat the slashes if necessary, maintain the caret location, and so on.And what do you want to happen if the user types
98/76/54
?Ideally (I expect) you will want to validate every "keystroke":
0
,1
,2
or3
1-9
if first char is0
0-9
if the first char is1
or2
0
or1
if the first char is3
0
or1
1-9
if first char is0
0
,1
or2
if the first char is1
and so on.
Of course, if the user types
02/3
or06/31
or05/38
(etc), you’ll also need to reject that last input.