swift UITextField限制
2020-09-15 本文已影响0人
喵喵粉
- 限制小数点后面2位
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else {
return true
}
//新输入的
if string.count == 0 {
return true
}
//判断新的文本内容是否符合要求
return isValid(text: text, replacementString: string, range: range)
}
///检测改变过的文本是否匹配正则表达式,如果匹配表示可以键入,否则不能键入
func isValid(text: String, replacementString string: String, range: NSRange) -> Bool {
//第一个参数,被替换字符串的range
//第二个参数,即将键入或者粘贴的string
//返回的是改变过后的新str,即textfield的新的文本内容
let checkStr = (text as NSString).replacingCharacters(in: range, with: string)
//正则表达式(只支持两位小数)
let regex = "^\\-?([1-9]\\d*|0)(\\.\\d{0,2})?$"
let predicte = NSPredicate(format:"SELF MATCHES %@", regex)
return predicte.evaluate(with: checkStr)
}
- 限制11位手机号
fileprivate func validateNumber(_ textField: UITextField, range: NSRange, string: String, limit: Int = 11) -> Bool {
guard let text = textField.text else { return false }
///拼接了参数string的afterStr
// let afterStr = text.replacingCharacters(in: text.ext2Range(range)!, with: string)
// DebugLog(afterStr)
let afterStr = (text as NSString).replacingCharacters(in: range, with: string)
DebugLog(afterStr)
///限制长度
if afterStr.count > limit {
textField.text = (afterStr as NSString).substring(to: limit)
return false
}
///是否都是数字
let set = CharacterSet(charactersIn: "0123456789").inverted
let filteredStr = string.components(separatedBy: set).joined(separator: "")
if filteredStr == string {
return true
}
return false
}