Swift UITextField输入框只允许输入数字和小数点
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
// 只允许输入数字和两位小数
let expression = "^[0-9]*((\\.|,)[0-9]{0,2})?$"
// let expression = "^[0-9]*([0-9])?$" 只允许输入纯数字
// let expression = "^[A-Za-z0-9]+$" //允许输入数字和字母
let regex = try! NSRegularExpression(pattern: expression, options: .allowCommentsAndWhitespace)
let numberOfMatches = regex.numberOfMatches(in: newString, options:.reportProgress, range:NSMakeRange(0, newString.count))
if numberOfMatches == 0{
print("请输入数字")
return false
}
return true
}