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

前端 未结 28 2153
长情又很酷
长情又很酷 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:48

    Swift 5.1, Xcode 11

    After trying many solutions, I faced issues such as setting correct cursor position and formating as per need, I finally found a solution after combining 2 posts (https://stackoverflow.com/a/38838740/10579134, https://stackoverflow.com/a/45297778/10579134)

    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 == yourTextField  {
    
            textField.setText(to: currentText.grouping(every: 4, with: "-"), preservingCursor: true)
    
            return false
        }
        return true
    }
    

    And adding this extension

    extension UITextField {
    
    public func setText(to newText: String, preservingCursor: Bool) {
        if preservingCursor {
            let cursorPosition = offset(from: beginningOfDocument, to: selectedTextRange!.start) + newText.count - (text?.count ?? 0)
            text = newText
            if let newPosition = self.position(from: beginningOfDocument, offset: cursorPosition) {
                selectedTextRange = textRange(from: newPosition, to: newPosition)
            }
        }
        else {
            text = newText
        }
    }
    

提交回复
热议问题