在文本框输入电话号码时,按照 3 4 4 的格式动态显示(如 130 1234 1234)
首先添加上UITextField的代理 UITextFieldDelegate
Swift
private var phoneContent = ""
private var previousSelection = UITextRange()
private lazy var textFieldPhone: UITextField = {
let newTextField = UITextField()
newTextField.delegate = self
newTextField.addTarget(self, action: #selector(textFieldChange(_:)), for: .editingChanged)
return newTextField
}()
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textFieldPhone == textField {
phoneContent = textField.text ?? ""
if phoneContent.count >= 13 && string.count > 0 {
print("手机号码为11位")
return false
}
previousSelection = textField.selectedTextRange ?? UITextRange()
}
return true
}
@objc func textFieldChange(_ textField: UITextField) {
let text = textField.text ?? ""
if textFieldPhone == textField