Search code examples
iphoneiosautocompleteuisearchbaruisearchdisplaycontroller

IOS: Autocomplete Search using UISearchbar


I have an NSMutableArray which consists of text fields. I want to load them when user types inside the UISearchBar. Initially I don't want to load all the text fields before user starts typing. Only user start typing the first letter suggestion need to be load. Any help?


Solution

  • There are many logic but i put my logic here :

    Take Two NSMutableArray and add one array to another array in ViewDidLoad method such like,

    self.listOfTemArray = [[NSMutableArray alloc] init]; // array no - 1
    self.ItemOfMainArray = [[NSMutableArray alloc] initWithObjects:@"YorArrayList", nil]; // array no - 2 
    
    [self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray]; // add 2array to 1 array
    

    And Write following delegate Method of UISearchBar

    - (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText
    {
            NSString *name = @"";
            NSString *firstLetter = @"";
    
        if (self.listOfTemArray.count > 0)
             [self.listOfTemArray removeAllObjects];
    
            if ([searchText length] > 0)
            {
                    for (int i = 0; i < [self.ItemOfMainArray count] ; i = i+1)
                    {
                            name = [self.ItemOfMainArray objectAtIndex:i];
    
                            if (name.length >= searchText.length)
                            {
                                    firstLetter = [name substringWithRange:NSMakeRange(0, [searchText length])];
                                    //NSLog(@"%@",firstLetter);
    
                                    if( [firstLetter caseInsensitiveCompare:searchText] == NSOrderedSame )
                                    {
                                        // strings are equal except for possibly case
                                        [self.listOfTemArray addObject: [self.ItemOfMainArray objectAtIndex:i]];
                                        NSLog(@"=========> %@",self.listOfTemArray);
                                    }
                             }
                     }
             }
             else
             {
                 [self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray ];
             }
    
            [self.tblView reloadData];
    }
    }
    

    Output Show in your Consol.

    This code might helpful for you.