iOS: How to avoid special characters being entered in a search bar?

让人想犯罪 __ 提交于 2019-12-11 08:44:57

问题


I may be looking at this incorrectly, but right now, if a user enters certain special characters in a search bar, the app will crash. These include \ and '.

The apostrophe is a problem, in that words like "isn't" and "doesn't" will cause a crash

How should I go about working around this problem?

Many thanks


回答1:


Before doing a search using the search string, pre-filter it, like this:

NSString *safeSearchString = [[searchString componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]] componentsJoinedByString:@""];



回答2:


Why don't you escape the characters and actually search for what the user wants instead of ignoring or removing what they want ?

Are you using SQLite ? If so then you can escape a single quote by another single quote.




回答3:


The UISearchBar utilizes the UISearchBarDelegate protocol. To stop users entering \ and ' all you need to do is to override the searchBar:shouldChangeTextInRange:replacementText: method and if you sense the special characters in the text, you simply return NO.

But handling (rather than ignoring) these special chars in your program is a better user experience. After all why are you users even searching for "isn't" and "doesn't" in the first place?



来源:https://stackoverflow.com/questions/9241139/ios-how-to-avoid-special-characters-being-entered-in-a-search-bar

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