how to show suggestion for UISearchBar search?

1.1k views Asked by At

I am making a demo Weather app, and inside this i am using UISearchBar so can user entry city name, but i don't know how to display suggestion for that.

For example, if user enters "lon" than there should be cities name suggesting start from "lon" like London, etc.

2

There are 2 answers

0
Andrea On BEST ANSWER

UISearchBar has its own delegation protocol UISearchBarDelegate, the method -

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

make possible while editing to do some extra operations, here you can put your NSPredicate to see if the inserted text has a city that BEGINSWITH or CONTAINS the entered text.

1
Devang Goswami On

You can do that by,

  1. create an array (List) of places to be shown ... add object in array !

    NSArray *list;

    NSArray *listFiles;

2.Filter the content ..

-(void)filter :(NSString *) match1


    listFiles = [[NSMutableDictionary alloc] init];

    NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"FullName BEGINSWITH[c] %@", match1];

    listFiles = [[ContactDect filteredArrayUsingPredicate:sPredicate ] mutableCopy];
    f_name_array=[[NSMutableArray alloc]init];

    for (NSDictionary *d in listFiles) {

        [self.f_name_array addObject:[d objectForKey:@"FullName"]];

    }
    list=f_name_array;
    NSLog(@"%@",list);



}
  1. then count list in numberOfRowsInTableview :

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [listFiles count]; }

  1. cellForRow ::::

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"abccell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; cell.textLabel.text = [NSString stringWithFormat:@"%@" ,[listFiles objectAtIndex:indexPath.row]]; return cell; }

Call the Filter method while editing textFeild !

[self filter:textfeild1.text];

I wish it will help you .....