UITextField format in xx-xx-xxx

后端 未结 10 1610
暖寄归人
暖寄归人 2020-11-27 04:13

I am using UITextField and i want that should take character in the format of xx-xx-xxx only numbers.

any help ?

10条回答
  •  有刺的猬
    2020-11-27 04:45

    Here is my take on it after looking at everyone's answers.

    Swift 4

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let separator = "-"
        let filler = "X"
        if var number = textField.text, string != "" {
            number = number.replacingOccurrences(of: separator, with: "")
            number = number.replacingOccurrences(of: filler, with: "")
            if number.count == 10 { return false }
            number += string
            while number.count < 10 { number += "X" }
            number.insert("-", at: number.index(number.startIndex,
                                                offsetBy: 6))
            number.insert("-", at: number.index(number.startIndex,
                                                offsetBy: 3))
            textField.text = number
        }
        return false
    }
    

提交回复
热议问题