本文介绍了如何快速制作信用卡(xxxx-xxxx-xxxx)文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码创建信用卡类型的文本,但无法执行此操作,有什么办法吗?

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)")
}

推荐答案

以下逻辑实现了带空格的16位简单信用卡格式.

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

代码已针对Swift 4/5进行了调整

第1步:为信用卡文本字段创建操作

Step 1: Create an action for for credit card textfield

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

第2步:从文本字段的选择器方法中调用一个将进行格式化的方法

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!)
}

第3步:实现方法"modifyCreditCardString"

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
 }

第4步:实现UITextField的委托,这将卡号限制为16个字符. 19 = 16 + 3(每4位数字后1个空格)

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

这篇关于如何快速制作信用卡(xxxx-xxxx-xxxx)文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 18:14