用UItextField的代理方法來(lái)限制字?jǐn)?shù)或即時(shí)判斷輸入內(nèi)容有效性等問(wèn)題的時(shí)候是不能完美滿足需求的帚豪,這篇文章介紹另一種方法可能對(duì)你有很大啟發(fā)狸臣。因?yàn)閁ItextField和UIbutton一樣是繼承于UIControl的昌执,所以是可以addTarget的,如下:
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
然后實(shí)現(xiàn)textFieldDidChange:的方法,這個(gè)方法在輸入或刪除每個(gè)字符的時(shí)候都會(huì)調(diào)用懂拾。
- (void)textFieldDidChange:(UITextField *)textField {
NSString *toBeString = [textField.text lowercaseString];
textField.text = toBeString;
//限制字?jǐn)?shù)
_limitNum = 16;
//獲取高亮部分
UITextRange *selectedRange = [textField markedTextRange];
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
// 沒(méi)有高亮選擇的字岖赋,則對(duì)已輸入的文字進(jìn)行字?jǐn)?shù)統(tǒng)計(jì)和限制
if (!position||!selectedRange)
{
if (toBeString.length > _limitNum)
{
NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:_limitNum];
if (rangeIndex.length == 1)
{
textField.text = [toBeString substringToIndex:_limitNum];
}
else
{
NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, _limitNum)];
textField.text = [toBeString substringWithRange:rangeRange];
}
}
}
//commitButton 是否可以點(diǎn)擊
if (_newPasswordTextField.text.length>5&&_confirmPasswordTextField.text.length>5&&_newPasswordTextField.text.length==_confirmPasswordTextField.text.length) {
_commitButton.backgroundColor = SAColorByRGB(0, 124, 246);
_commitButton.userInteractionEnabled = YES;
}else{
_commitButton.backgroundColor = SAColorByRGB(219, 219, 219);
_commitButton.userInteractionEnabled = NO;
}
//實(shí)時(shí)查看密碼格式是否正確
if (textField == _newPasswordTextField) {
if (_newPasswordTextField.text.length>5) {
if ([self isNumberWithLetterType:_newPasswordTextField.text]) {
_newPasswordTextField.type = SAFloatLabeledTextFieldTypeNormal;
}else{
_newPasswordTextField.type = SAFloatLabeledTextFieldTypeWrong;
}
}else{
_newPasswordTextField.type = SAFloatLabeledTextFieldTypeNormal;
}
}
}
/** 判斷是否是數(shù)字+字母 16位*/
- (BOOL)isNumberWithLetterType:(NSString *)string {
NSString *regex = @"(?=.*\\d)(?=.*[a-zA-Z]).{1,16}";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
return [pred evaluateWithObject:string];
}