???????做項(xiàng)目的時(shí)候遇到這樣一個(gè)小問題恬试,因?yàn)樾枨蟮木壒饰倚枰獎討B(tài)監(jiān)聽UITextField輸入內(nèi)容的變化,可是在使用蘋果官方提供的API發(fā)現(xiàn)是可以監(jiān)聽內(nèi)容的變化毫胜,可是不是太準(zhǔn)確于是就在網(wǎng)上搜了半天找到了解決方法叫乌,在這里和大家分享一下吧!
???
問題描述:
?????????使用下邊方法動態(tài)監(jiān)聽UITextField輸入內(nèi)容的變化不準(zhǔn)確墨缘。
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSLog(@"%@",textField.text);
return YES;
}
解決方案:
?????????直接添加一個(gè)事件,不過需要注意控件事件需要填寫:UIControlEventEditingChanged
否則無效。
UITextField *testField =[[UITextField alloc]init];
[testField addTarget:self action:@selector(testFieldChangeEvent:) forControlEvents:UIControlEventEditingChanged];
-(void)testFieldChangeEvent:( UITextField*)textField{
NSLog(@"sender->:%@",textField.text);
}
UITextField小知識點(diǎn)
#限制輸入U(xiǎn)ITextField輸入內(nèi)容的長度
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSInteger kMaxLength = 5;//限制的長度
NSInteger strLength = textField.text.length - range.length + string.length;
return (strLength <= kMaxLength );