Cx330

输入框在手机号上的特殊处理

2017-09-12 · 1 min read
iOS

有时候需求需要我们把手机号码在输入时做特殊处理,比如这样

extension String {
    func formatPhoneNumberWithOriginalPhoneNumber() -> String {
        var text = self
        if text.contains(" ")  {
            text = text.replacingOccurrences(of: " ", with: "")
        }
        var res = text
        if text.length > 3 {
            res.insert(" ", at: text.index(text.startIndex, offsetBy: 3))
            if text.length >= 9 {
                res.insert(" ", at: res.index(text.startIndex, offsetBy: 8))
            }
        }
        
        return res
    }
}

!!!敲黑板,划重点

以下这段不是UITextFieldDelegate

它是给你的输入框添加的事件,当然你也可以用监听

textField.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
func textFieldDidChange(_ textField: UITextField) {
    if let text = textField.text {
        if phoneTextField == textField {
            phoneTextField.text = text.formatPhoneNumberWithOriginalPhoneNumber()
        }
    }
}