UISearchBar that Ignores Special Characters when Searching UITableView Cell

北慕城南 提交于 2019-12-04 19:39:26

This one is a little tricky. The first solution that comes to mind is to strip any character that you deliberately don't want to match from both the search and item strings, then do the comparison. You can use NSCharacterSet instances to do that filtering:

// Use this method to filter all instances of unwanted characters from `str`
- (NSString *)string:(NSString *)str filteringCharactersInSet:(NSCharacterSet *)set {
    return [[str componentsSeparatedByCharactersInSet:set]
            componentsJoinedByString:@""];
}

// Then, in your search function....
NSCharacterSet *unwantedCharacters = [[NSCharacterSet alphanumericCharacterSet] 
                                      invertedSet];
NSString *strippedItemName = [self string:[item objectForKey:@"name"] 
                 filteringCharactersInSet:unwantedCharacters];
NSString *strippedSearch = [self string:searchText
               filteringCharactersInSet:unwantedCharacters];

Once you have the stripped strings, you can do your search, using strippedItemName in place of [item objectForKey:@"name"] and strippedSearch in place of searchText.

In your example, this would:

  • Translate the search string "Jims Event" to "JimsEvent" (stripping the space)
  • Translate an item "Jim's Event" to "JimsEvent" (stripping the apostrophe and space)
  • Match the two, since they're the same string

You might consider stripping your search text of unwanted characters once, before you loop over item names, rather than redoing the same work every iteration of your loop. You can also filter more or fewer characters by using a set other than alphanumericCharacterSet - take a look at the class reference for more.

Edit: we need to use a custom function to get rid of all characters in the given set. Just using -[NSString stringByTrimmingCharactersInSet:] only filters from the ends of the string, not anywhere in the string. We get around that by splitting the original string on the unwanted characters (dropping them in the process), then rejoining the components with an empty string.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!