iOS开发_Objective-C_监听搜索时用户输入的拼音

实现这个功能其实很简单, 只需要一下这几部就可以实现


1. 为了监听并保存用户输入的拼音, 首先我们需要在类的 .m 文件中声明一个成员变量:

 1 @property (nonatomic, strong) NSMutableString *currentSearchText; 


2. 设置 UISearchBar 的代理为当前类:

 1 self.searchBar.delegate = self; 


3. 实现 UISearchBar 的代理方法:

 1 - (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

 2 

 3     

 4 

 5     if (!range.length) { // 代表用户输入的字符

 6 

 7         [self.currentSearchText appendFormat:@"%@", text]; // 给当前搜索的字符串拼接字符

 8 

 9     } else { // 表示用户删除了一个字符

10 

11         [self.currentSearchText  deleteCharactersInRange:NSMakeRange(self.currentSearchText.length-1,1)]; // 删除当前搜索字符串最后一个字符

12 

13     }

14 

15 

16      [self beginSearch: self.currentSearchText];

17 

18  

19 

20 return YES;

21 

22 }
SearchBar Delegate


4. 根据需求的不同, 可以选择实现下面这个代理方法:

1 - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString*)searchText {

2 

3     

4 

5     self.currentSearchText = [NSMutableString stringWithFormat:@"%@", searchText]; // 将用户输入的文字保存到 当前搜索的字符串中.

6 

7 }
SearchBar Delegate


以上这几部可以实现 用户拼音输入法 输入文字的时候, 直接进行搜索, 而无需用户选择文字之后再进行搜索.

你可能感兴趣的:(Objective-C)