3

I've a tableview and text field where I've implemented search method. Right now, when I write some value in textfield and click search button, then it search in the tableview. But, I want it to be dynamic means the moment I start typing in textfield it should start searching without clicking any button.

How can I do this?

Ekta Padaliya
  • 5,743
  • 3
  • 39
  • 51
Nilesh Jha
  • 1,626
  • 19
  • 35

3 Answers3

3

To implement dynamic search in the ios, we can also use textbox as search bar.

Go to StoryBoard and do the following changes

  1. Add the textbox to the view controller and assign the outlets and delegates.
  2. now to viewcontroller.m and paste the following code

-(void)textFieldDidChange:(UITextField *)textField
{
    searchTextString=textField.text;

    [self updateSearchArray:searchTextString];
}


-(void)updateSearchArray:(NSString *)searchText
{
    
    if(searchText.length==0)
   {
        isFilter=NO;    }
    else{
      
       isFilter=YES;
        
       searchArray=[[NSMutableArray alloc]init];
        
        for(NSString *string in responceArray){

        NSRange stringRange = [[NSString stringWithFormat:@"%@",string]
                               rangeOfString:searchtext.text options:NSCaseInsensitiveSearch];
            
        if (stringRange.location != NSNotFound) {
            [searchArray addObject:string];

        }
            
        }
        
        [jobsTable reloadData];
    }
    
    }
Purushothaman
  • 358
  • 4
  • 22
2

Connect method that do the same as on click to the event Value changed (see in the screenshot at the very bottom) in connections inspector.

enter image description here

Oleshko
  • 2,923
  • 4
  • 17
  • 25
  • @NileshJha if my answer solved your problem - could you, please, accept it (it may be helpful to others people)? – Oleshko Dec 20 '15 at 20:00
2

Just Connect this method on Editing Changed Event of your TextField. So, this method is called when you are changing its value.

- (IBAction)txtValueChanged:(UITextField)sender
{
    [self dynamicSearchInto:sender.text];
    //From here, we are passing text of textField.
}

Here, allData is an array which contains all your data. And searchArray is an array in which contains only searching data. So make sure that, you have to set count of searchArray into tableview's rows count. And setting data into tableview according to this searchArray.

-(void)dynamicSearchInto:(NSString *)strText
{
    if (strText.length != 0)
    {
        searchArray = [[NSArray alloc]init];
        NSString *str=txtSearch.text;
        NSPredicate *predicate=[NSPredicate predicateWithFormat:@"SELF['yourKey'] contains[c] %@", str];
        searchArray = [allData filteredArrayUsingPredicate:predicate];
        [myTableView reloadData];
    }
    else
    {
        searchArray = allData;
    }
    [myTableView reloadData];
}

Hope, this is what you're looking for. Any concern get back to me.

Meet Doshi
  • 4,241
  • 10
  • 40
  • 81