Formatting a UITextField for credit card input like (xxxx xxxx xxxx xxxx)

前端 未结 28 2166
长情又很酷
长情又很酷 2020-11-28 01:19

I want to format a UITextField for entering a credit card number into such that it only allows digits to be entered and automatically inserts spaces so that the

28条回答
  •  半阙折子戏
    2020-11-28 01:35

    So I wanted to this with less code, so I used the code here and repurposed it a little bit. I had two fields in the screen, one for the number and one for the expiry date, so I made it more reusable.

    Swift 3 alternate answer

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let currentText = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) else { return true }
    
        if textField == cardNumberTextField {
            textField.text = currentText.grouping(every: 4, with: " ")
            return false
        }
        else { // Expiry Date Text Field
            textField.text = currentText.grouping(every: 2, with: "/")
            return false
        }
    }
    
    extension String {
        func grouping(every groupSize: String.IndexDistance, with separator: Character) -> String {
           let cleanedUpCopy = replacingOccurrences(of: String(separator), with: "")
           return String(cleanedUpCopy.characters.enumerated().map() {
                $0.offset % groupSize == 0 ? [separator, $0.element] : [$0.element]
           }.joined().dropFirst())
        }
    }
    

提交回复
热议问题