extension LoginViewController:UITextFieldDelegate {
/**
* 问题:
* 1.目前没有限制手机号输入时位数(11位),只在最后做校验
* 2.从手机通讯录复制的手机号存在前缀编码和后缀编码,导致手机号校验失败
*
*/
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.count == 0 {
return true
}else {
if let text = textField.text {
let textLength = text.count
let finalString = string.getNumber()
let finalStringLength = finalString.count
if finalStringLength == 0 {
return false
}
if textLength < phoneLimit {
let spaceLength = phoneLimit - textLength
if finalStringLength > spaceLength {
textField.text = text + finalString.prefix(spaceLength)
return false
}else {
textField.text = text + finalString
return false
}
}
return false
}
}
return true
}
}
func getNumber() -> String {
let chartSet = CharacterSet(charactersIn: "0123456789").inverted
let string = self.components(separatedBy: chartSet).joined(separator: "")
return string
}
网友评论