如何在swift中输入信用卡(xxxx-xxxx-xxxx)文本

时间:2016-05-12 14:56:49

标签: swift2

我正在尝试使用以下代码创建信用卡类型文本,但无法做到这一点,有什么办法吗?

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

1 个答案:

答案 0 :(得分:7)

这是快速快速3版本的答案。此逻辑实现了带空格的简单16位信用卡格式。

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

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

步骤2:从将执行格式化的文本字段选择器方法调用方法

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

步骤3:实施方法" modifyCreditCardString"

func modifyCreditCardString(creditCardString : String) -> String
{
    let trimmedString = creditCardString.components(separatedBy: .whitespaces).joined()

    let arrOfCharacters = Array(trimmedString.characters)

    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的委托

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
    let newLength = textField.text!.characters.count + string.characters.count - range.length

    if(textField == txtFieldCreditCardNumber)
    {
        return newLength <= 19
    }
    return true
}

就是这样。感谢