Sometimes a UITableView needs to have a lot of rows of information. The main problem that arises with having a table view with lots and lots of rows in it is the accessibility of the rows. Imagine a contact book in your phone with 500+ phone numbers.Searching for a particular phone number in the that contact book will be a nightmare and it will be really exhausting and not very userfriendly.
Therefore a developer might want to put a search bar to search for the contents in a table view. The search bar is very helpful if the table view have hundreds of cells.
one of the methods is the simple concept of accepting the string from the user and match it with data of the table view. This method while simple to use and friendly to the programmer is not very friendly for the user. Because a single letter missed in the search string will change the result completely and the user has to cancel the search and try again. It gets more frustrating if the user does not know the actual word he is looking for and remembers just a fragment of the string. For example "The surname of an old colleague".
The answer to this problem is to accept the string from the user and refresh the search, and display all the cells containing the letter. This has to be done after every letter is typed and also after every letter is deleted.
For example if the user types in letter M, the table displays all the names containing M in it.
(Mike, Milli, Miley, Mac, Mona, Max, Mathew, Matt, Megan).
next when the user types i, the table is again refreshed with the new results which contains only words containing the letters M and i.
(Mike, Mille, Miley)
This will go on till the user gets the required cell, and will make sure that the user gets all the options of choosing the from the cells that may be the correct option.
This method is incredibly simple and easy to implement. All the developer has to do is use the delegate methods of UISearchBar and the delegate methods does all the work for you.
#pragma mark Search Bar delagates
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar;
{
// return YES to begin editing
return YES;
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar;
{
// return NO to not resign first responder
return NO;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
{
// called when the user stars to type in the search bar
[tableArray removeAllObjects];
for (NSString *string in dataArray)
{
NSRange range = [string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (range.length>0) {
[tableArray addObject:string];
}
}
[[self myTableView] reloadData];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar;
{
// called when search button is clicked
[tableArray removeAllObjects];
for (NSString *string in dataArray) {
NSRange range = [string rangeOfString:searchBar.text options:NSCaseInsensitiveSearch];
if (range.length>0) {
[tableArray addObject:string];
}
}
[[self myTableView] reloadData];
}
0 Comment(s)