manatee manatee - 1 year ago 65
iOS Question

How do I configure the text field to account for the expiry date?

I am entering credit card information and I want the expiry date to be a max of 5 characters 4 numbers and a "/" automatically enters after the first two characters i.e. 01/17 after typing 01 the / is automatically entered, and allows only two more characters "17".

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
if textField == expire{

}
return true
}

Answer Source

Try like this, Its working at my end.

 func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
    //Range.Lenth will greater than 0 if user is deleting text - Allow it to replce
    if range.length > 0
    {
        return true
    }

    //Dont allow empty strings
    if string == " "
    {
        return false
    }

    //Check for max length including the spacers we added
    if range.location >= 5
    {
        return false
    }

    var originalText = textField.text
    let replacementText = string.stringByReplacingOccurrencesOfString(" ", withString: "")

    //Verify entered text is a numeric value
    let digits = NSCharacterSet.decimalDigitCharacterSet()
    for char in replacementText.unicodeScalars
    {
        if !digits.longCharacterIsMember(char.value)
        {
            return false
        }
    }

    //Put / space after 2 digit
    if range.location == 2
    {
        originalText?.appendContentsOf("/")
        textField.text = originalText
    }

    return true
}

Hope this help you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download