用 UITextField 自定义的 UISearchBar 没有如下的 UISearchBar 中的协议方法
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
UITextField 中只有协议方法:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
该方法只能监听将要改变之前的状态,不能监听当前 textfield 的字符串,监听的字符串总是慢一步。如果将要输入中文,则监听到的是中文拼音,并且拼音中间以空格隔开,textField.text.length长度为英文字母加空格个数。
解决办法:
UITextFieldTextDidChangeNotification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(textChanged)
name:UITextFieldTextDidChangeNotification
object:_searchTF];
-(void)textChanged
{
BOOL isEqual = [_searchTF.text isEqualToString:_oldStr];
if ( isEqual || ((!isEqual) && (_oldStr.length > _searchTF.text.length))) {
NSLog(@"===%@=========",_searchTF.text);
}
_oldStr = _searchTF.text;
}
//或者
-(void)textChanged
{
if ([_searchTF.text isEqualToString:_oldStr]) {
NSLog(@"===%@=========",_searchTF.text);
}
if ((![_searchTF.text isEqualToString:_oldStr])&&(_oldStr.length > _searchTF.text.length)) {
NSLog(@"===%@=========",_searchTF.text);
}
_oldStr = _searchTF.text;
}
更正:
-(void)textChanged
{
if ([_searchTF.text isEqualToString:_changeStr]) {
// [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// [_doctorsArray removeAllObjects];
// [self loadDoctorWithKeyword:_searchTF.text AndIsSearchType:YES AndPage:1];
_oldStr = _searchTF.text;
NSLog(@"===%@=========",_searchTF.text);
}else if ((![_searchTF.text isEqualToString:_oldStr])&&(_oldStr.length > _searchTF.text.length)) {
// [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// [_doctorsArray removeAllObjects];
// [self loadDoctorWithKeyword:_searchTF.text AndIsSearchType:YES AndPage:1];
_oldStr = _searchTF.text;
NSLog(@"===%@=========",_searchTF.text);
}
_changeStr = _searchTF.text;
}
-(void)textChanged
{
BOOL isEqual = [_searchTF.text isEqualToString:_changeStr];
if ( isEqual || ((!isEqual) && (_oldStr.length > _searchTF.text.length))) {
_oldStr = _searchTF.text;
NSLog(@"===%@=========",_searchTF.text);
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[_doctorsArray removeAllObjects];
[self loadDoctorWithKeyword:_searchTF.text AndIsSearchType:YES AndPage:1];
}
_changeStr = _searchTF.text;
}