判断textfeild输入纯数字,长度为11

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])?$"

    let regex = try! NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.allowCommentsAndWhitespace)
    
    let numberOfMatches = regex.numberOfMatches(in: newString, options:NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (newString as NSString).length))

    if textField.text!.count == 11 {
        if string.isEmpty {
           return true
        }else {
            return false
        }
    }else {
        return numberOfMatches != 0
    }

}

你可能感兴趣的:(判断textfeild输入纯数字,长度为11)