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

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

    Swift 3.2

    Little correction in the @Lucas answer and working code in swift 3.2. Also removing the space character automatically.

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
        if range.location == 19 {
            return false
        }
    
        if range.length == 1 {
            if (range.location == 5 || range.location == 10 || range.location == 15) {
                let text = textField.text ?? ""
                textField.text = text.substring(to: text.index(before: text.endIndex))
            }
            return true
        }
    
        if (range.location == 4 || range.location == 9 || range.location == 14) {
            textField.text = String(format: "%@ ", textField.text ?? "")
        }
    
        return true
    }
    

提交回复
热议问题