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

前端 未结 28 2195
长情又很酷
长情又很酷 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:41

    here is the modification of the answer from @sleeping_giant for swift. This solution formats the text in 'xxxx-xxxx-xxxx-xxxx-xxxx' format and stops accepting any numbers beyond that range.

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
    {
        if string == ""{
            return true
        }
    
        //range.length will be greater than 0 if user is deleting text - allow it to replace
        if range.length > 0
        {
            return true
        }
    
        //Don't allow empty strings
        if string == "-"
        {
            return false
        }
    
        //Check for max length including the spacers we added
        print(range.location)
        if range.location > 23
        {
            return false
        }
    
        var originalText = textField.text
        let replacementText = string.replacingOccurrences(of: "-", with: "")
    
        //Verify entered text is a numeric value
        let digits = NSCharacterSet.decimalDigits
        for char in replacementText.unicodeScalars
        {
            if !(digits as NSCharacterSet).longCharacterIsMember(char.value)
            {
                return false
            }
        }
    
        //Put an empty space after every 4 places
        if (originalText?.characters.count)! > 0
        {
            if (originalText?.characters.count)! < 5 && (originalText?.characters.count)! % 4 == 0{
                originalText?.append("-")
            }else if(((originalText?.characters.count)! + 1) % 5 == 0){
                originalText?.append("-")
            }
    
        }
    
        textField.text = originalText
    
        return true
    }
    

提交回复
热议问题