Home / IOS Development / ios – How can I get this functionality to set DOB in UITextField

ios – How can I get this functionality to set DOB in UITextField

enter image description here

I used a variable to store the text that was entered and change it by adding the remaining suffix “mm / dd / yyyy”

;. I get the functionality, but if I try to update the cursor to the correct position, it creates a problem. I used textfield.selectedTextRange to move the cursor from EOF to the position I need. But it replaces the text entered with the last “y” from “mm / dd / yyyy”. So if I type “12”, the text changes from mm / dd / yyyy | to “yyyy / mm / yyyy” instead of “12 | / dd / yyyy”

Am I doing it the wrong way?

let dobPlaceholderText = "mm/dd/yyyy"
var enteredDOBText = ""

@objc func textFieldDidChange(_ textField: UITextField){
    enteredDOBText.append(textField.text.last ?? Character(""))
    let modifiedText = enteredDOBText + dobPlaceholderText.suffix(dobPlaceholderText.count - enteredDOBText.count)
    textField.text = modifiedText
    setCursorPosition(input: dob.textField, position: enteredDOBText.count)
private func setCursorPosition(input: UITextField, position: Int){
    let position = input.position(from: input.beginningOfDocument, offset: position)!
    input.selectedTextRange = input.textRange(from: position, to: position)

Source link