格式化用于(xxxx xxxx xxxx xxxx)信用卡输入的NSTextField [macOS Swift]

时间:2019-06-23 05:46:10

标签: swift string macos cocoa string-formatting

我想格式化NSTextField以用于信用卡输入,例如(xxxx xxxx xxxx xxxx) 我尝试了以下代码

   func controlTextDidChange(_ obj: Notification){
   let number = card.stringValue.replacingOccurrences(of: " ", with: "")

    if(number.count % 4 == 0){
        card.stringValue = card.stringValue+" "
    }
  }

这很好,但是当我给一个退格键时,我似乎有问题。

有没有更好的方式格式化我的字符串

1 个答案:

答案 0 :(得分:-1)

我正在使用UITextField,但我认为它与NSTextField

非常相似
// remember to do this
textField.delegate = self

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let number = textField.text?.replacingOccurrences(of: " ", with: "")
    if ((number?.count ?? 0) % 4 == 0 && string != "") {
        textField.text! += " "
    }

    return true
}