Notification texts go here Contact Us Buy Now!

Entering Date in dd-MM-yyyy format using numeric keyboard in UITextField swift 3.0

Swift 3.0

// create one textfield
@IBOutlet var txtDOB: UITextField!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    // set delegate for your textfield
    txtDOB.delegate = self

}

// call your function in textfield delegate shouldChangeCharactersIn

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    //Format Date of Birth dd-MM-yyyy

    //initially identify your textfield

    if textField == txtDOB {

        // check the chars length dd -->2 at the same time calculate the dd-MM --> 5
        if (txtDOB?.text?.characters.count == 2) || (txtDOB?.text?.characters.count == 5) {
            //Handle backspace being pressed
            if !(string == "") {
                // append the text
                txtDOB?.text = (txtDOB?.text)! + "-"
            }
        }
        // check the condition not exceed 9 chars
        return !(textField.text!.characters.count > 9 && (string.characters.count ) > range.length)
    }
    else {
        return true
    }
}

ObjectiveC

  - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
  {
//Format Date of Birth dd-MM-yyyy

 if(textField == txtDOB)
    {
    if ((txtDOB.text.length == 2)||(txtDOB.text.length == 5))
        //Handle backspace being pressed
        if (![string isEqualToString:@""])
            txtDOB.text = [txtDOB.text stringByAppendingString:@"-"];
    return !([textField.text length]>9 && [string length] > range.length);
}
else
    return YES;

}

Swift 5

if textField == dateTextField {
            if dateTextField.text?.count == 2 || dateTextField.text?.count == 5 {
                //Handle backspace being pressed
                if !(string == "") {
                    // append the text
                    dateTextField.text = dateTextField.text! + "."
                }
            }
            // check the condition not exceed 9 chars
            return !(textField.text!.count > 9 && (string.count ) > range.length)
        } else {
            return true
        }

SwiftUI

struct DobScreen: View {
@State private var dobText: String = ""
@State var textLen = 0

var body: some View {
        VStack(alignment: .leading) {
            TextField("MM-DD-YYYY", text: $dobText)
            .onChange(of: dobText) { newValue in
                
                if newValue.count < textLen {
                    // If the length of the new value is less than the previous length,
                    // it indicates a deletion (backspace).
                    dobText = ""
                    textLen = 0
                    return
                }
                // Check if the input length exceeds 10 characters
                 guard newValue.count <= 10 else {
                     dobText = String(newValue.prefix(10))
                     return
                 }
                
                 // Handle backspace
                 if newValue.count < dobText.count {
                     // If the length of the new value is less than the previous length,
                     // it indicates a deletion (backspace).
                     dobText = ""
                     return
                 }
                 
                 // Add separators for MM / DD / YYYY format
                 if newValue.count >= 2 && !newValue.contains("-") {
                     dobText.insert("-", at: dobText.index(dobText.startIndex, offsetBy: 2))
                 }
                 if newValue.count >= 5 && !newValue[dobText.index(dobText.startIndex, offsetBy: 5)...].contains("-") {
                     dobText.insert("-", at: dobText.index(dobText.startIndex, offsetBy: 5))
                 }
                textLen = dobText.count
            }
        }.padding()
    }
}

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.