【问题标题】:How to deal with searching piece of word in word with UISearchBar and UITableView?如何处理用 UISearchBar 和 UITableView 逐字搜索?
【发布时间】:2013-01-07 23:17:57
【问题描述】:

我是 UISearchBar 的新手,我有一些用于搜索单词的代码。

- (void)searchTableView
{
NSLog(@"Searching...");
NSString *searchText = searchBar.text;

NSMutableArray *tempSearch = [[NSMutableArray alloc] init];

for (NSDictionary *item in items) {

    if ([[item objectForKey:@"en"] isEqualToString:searchText]) {
        NSLog(@"Found");

        [tempSearch addObject:item];
    }
}

searchArray = [tempSearch copy];
}

它有效,但问题是它仅适用于完整的单词(例如,如果在UITableViewCell 中的textLabel 中是文本“something”并且我在UISearchBar 中输入“something”,那么我已经返回了这一行,但是当我输入“some”时,当完整的单词是“some”时,我有行,“something”没有显示)。我怎样才能用我的方法搜索正确的文本?

【问题讨论】:

    标签: objective-c uitableview search uisearchbar words


    【解决方案1】:

    使用NSPredicate 可以稍微简化搜索:

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"en BEGINSWITH %@", searchText];
    NSArray *tempSearch = [items filteredArrayUsingPredicate:predicate];
    

    如果您想要不区分大小写的搜索,请将BEGINSWITH 替换为BEGINSWITH[c]

    有关详细信息,请参阅“谓词编程指南”中的 Using Predicates

    【讨论】:

      【解决方案2】:

      好的,我有一些东西,但不是 100% 正确。

      for (NSDictionary *item in items) {
      
          NSRange range = [[item objectForKey:@"en"] rangeOfString : searchText];
          if (range.location != NSNotFound) {
      
              NSLog(@"Found");
      
              [tempSearch addObject:item];
          }
      }
      

      当我输入“e”时,我得到了“some”、“something”、“else”——我认为正确的是只有“else”会被返回。

      好的,我知道了。

          if (range.location != NSNotFound && range.location == 0) {
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-17
        • 1970-01-01
        • 2011-08-02
        • 1970-01-01
        • 1970-01-01
        • 2018-08-30
        相关资源
        最近更新 更多