3

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: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let formatter = NSNumberFormatter()

    formatter.groupingSize = 4
    formatter.groupingSeparator = "-"
    formatter.usesGroupingSeparator = true

    print("txtCardNumber \(txtCardNumber.text)")
}
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
New iOS Dev
  • 1,937
  • 7
  • 33
  • 67
  • 2
    Possible duplicate of [Formatting a UITextField for credit card input like (xxxx xxxx xxxx xxxx)](http://stackoverflow.com/questions/12083605/formatting-a-uitextfield-for-credit-card-input-like-xxxx-xxxx-xxxx-xxxx) – Pekka May 12 '16 at 14:58
  • 1
    Its not duplicate as this answer is in objective-c language with some lengthy logic..i am trying to do in swift with standard logic – New iOS Dev May 12 '16 at 18:17
  • The question has Swift answers, too. Googleing your question title brings up more good results. You may have to rewrite them a little bit but what's out there looks really reasonable. – Pekka May 12 '16 at 18:21
  • @Pekka웃 Yes you are right, Thank you :) – New iOS Dev May 13 '16 at 04:19

1 Answers1

22

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

Teena nath Paul
  • 2,219
  • 23
  • 28