Formatting a UITextField for credit card input like (xxxx xxxx xxxx xxxx)

前端 未结 28 2120
长情又很酷
长情又很酷 2020-11-28 01:19

I want to format a UITextField for entering a credit card number into such that it only allows digits to be entered and automatically inserts spaces so that the

28条回答
  •  庸人自扰
    2020-11-28 01:37

    Please check bellow solution, its working fine for me-

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    
            let subString = (textField.text as! NSString).substringWithRange(range)
            if subString == " " && textField == cardNumberTextfield
            {
                return false     // user should not be able to delete space from card field
            }
            else if string == ""
            {
                return true      // user can delete any digit
            }
    
    
            // Expiry date formatting
    
            if textField == expiryDateTextfield
            {
                let str = textField.text! + string
    
                if str.length == 2 && Int(str) > 12
                {
                    return false                  // Month should be <= 12
                }
                else if str.length == 2
                {
                    textField.text = str+"/"      // append / after month
                    return false
                }
                else if str.length > 5
                {
                    return false                  // year should be in yy format
                }
            }
    
    
    
            // Card number formatting
    
            if textField == cardNumberTextfield
            {
                let str = textField.text! + string
    
                let stringWithoutSpace = str.stringByReplacingOccurrencesOfString(" ", withString: "")
    
                if stringWithoutSpace.length % 4 == 0 && (range.location == textField.text?.length)
                {
                    if stringWithoutSpace.length != 16
                    {
                        textField.text = str+" "    // add space after every 4 characters
                    }
                    else
                    {
                        textField.text = str       // space should not be appended with last digit
                    }
    
                    return false
                }
                else if str.length > 19
                {
                    return false
                }
            }
    
    
    
            return true
        }
    

提交回复
热议问题