How to make credit card (xxxx-xxxx-xxxx) type text in swift

前端 未结 1 1060
南旧
南旧 2021-01-01 07:13

I am trying to create credit card type text with following code, but not able to do that, is there any way to do?

func textField(textField: UITextFiel         


        
相关标签:
1条回答
  • 2021-01-01 07:52

    Below logic implements simple 16 digits credit card formatting with spaces.

    Edit: Code adjusted for Swift 4/5

    Step 1: Create an action for for credit card textfield

    self.txtFieldCreditCardNumber.addTarget(self, action: #selector(didChangeText(textField:)), for: .editingChanged)
    

    Step 2: Call a method from this selector method of textfield that will do the formatting

    @objc func didChangeText(textField:UITextField) {
        textField.text = self.modifyCreditCardString(creditCardString: textField.text!)
    }
    

    Step 3: Implement the method "modifyCreditCardString"

    func modifyCreditCardString(creditCardString : String) -> String {
         let trimmedString = creditCardString.components(separatedBy: .whitespaces).joined()
    
         let arrOfCharacters = Array(trimmedString)
         var modifiedCreditCardString = ""
    
         if(arrOfCharacters.count > 0) {
             for i in 0...arrOfCharacters.count-1 {
                 modifiedCreditCardString.append(arrOfCharacters[i])
                 if((i+1) % 4 == 0 && i+1 != arrOfCharacters.count){
                     modifiedCreditCardString.append(" ")
                 }
             }
         }
         return modifiedCreditCardString
     }
    

    Step 4: Implement the delegate of UITextField, which will restrict the card numbers to 16 characters. 19 = 16 + 3 (1 spaces after each 4 digits)

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
         let newLength = (textField.text ?? "").count + string.count - range.length
         if(textField == txtFieldCreditCardNumber) {
             return newLength <= 19
         }
         return true
    }
    

    Hope this will help. Thanks

    0 讨论(0)
提交回复
热议问题