我只想知道如何验证Textfield中的数字。我有一个UiTextField,我必须输入16位数字,而输入我可以重复相同的数字最多6次,当用户尝试输入超过6倍相同的数字意味着我需要显示警告
接受示例1231125641678923的2277890652222256其不被接受见数字2重复超过6次
这里是我的示例代码,但它不适合我
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// var ErrorAlert:UIAlertView!
if textField == sampleTextField{
var updatedTextString : NSString = textField.text! as NSString
updatedTextString = updatedTextString.stringByReplacingCharactersInRange(range, withString: string)
if textField.text!.containsString(string) {
// ErrorAlert=UIAlertView.init(title: "Error!", message: "please Enter Valid Policy Number", delegate: nil, cancelButtonTitle: "Ok")
// ErrorAlert.show()
NSLog("error")
}
}
答案 0 :(得分:2)
var number = "1123455324222323"
for digit in 0...9
{
if number.componentsSeparatedByString("\(digit)").count > 7
{ print("found more than 6 times : \(digit)") }
}
答案 1 :(得分:0)
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
var updatedTextString : NSString = textField.text! as NSString
updatedTextString = updatedTextString.stringByReplacingCharactersInRange(range, withString: string)
if (textField.text!.rangeOfString(string, options: .CaseInsensitiveSearch, range: nil, locale: nil) != nil) {
var length:NSInteger = string.characters.count
let str:Character = string[advance(string.startIndex, count(string)-1)]
var integerCount:NSInteger = 0
for digit in 0...count(string)-1
{
let str1:Character = string[advance(string.startIndex, digit)]
if (str == str1)
{
integerCount++
}
}
if(integerCount > 6)
{
return false
}
else
{
return true
}
}
return true
}