how to search tableview content in iOS?

2019-08-04 09:32发布

问题:

i am displaying list of content in my table view now i want to search that list content using uisearchbar i am implemented this code but its not work. .

     -(void)SearchBarCode

     {   self.disableViewOverlay = [[UIView 
         alloc]initWithFrame:CGRectMake(0.0f,44.0f,320.0f,0)];
         self.disableViewOverlay.backgroundColor=[UIColor lightGrayColor];
         self.disableViewOverlay.alpha = 0;

         theSearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 5, 374.0f, 
         50)];
         theSearchBar.delegate =self;
        [self.tableView addSubview:theSearchBar];
         self.navigationItem.title=@"SMS LIST";

        [[self tableView] setTableHeaderView:theSearchBar];

          }

      - (void)viewDidAppear:(BOOL)animated
       {
   [super viewDidAppear:animated];
  [self.theSearchBar resignFirstResponder];
       }


   - (void) dismissKeyboard
     {
       [self.theSearchBar becomeFirstResponder];
     } 


    - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
     {
        [theSearchBar setShowsCancelButton:YES animated:YES];

     }
    -(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
    {
       [theSearchBar resignFirstResponder];
        [self.view endEditing:YES];

     }
     - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
      {



      [theSearchBar setShowsCancelButton: YES animated: YES];
     //  [ self:filteredContentList];
      if (!theSearchBar.text || self.theSearchBar.text.length < 1)
       {
    [searchBar resignFirstResponder];
      }

       }

// ********* this textDidchange method *********************

     - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText

   {

   NSString *searchString =searchBar.text;
  filteredContentList = [[NSMutableArray alloc]init];
  [filteredContentList   removeAllObjects];
   for (SmsTitle *title in array)
  {
    NSString *tempStr = title.Title;
    NSComparisonResult result = [tempStr compare:searchString options:  
   (NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, 
   [searchString length])];

    if (result == NSOrderedSame)
    {

        [filteredContentList addObject:title];
    }
    }
    [self searchBarSearchButtonClicked:searchBar];
    }



     - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
    {
   theSearchBar.text=nil;
  [theSearchBar setShowsCancelButton:NO animated:YES];
  [theSearchBar resignFirstResponder];
  }

   - (void)searchBar:(UISearchBar *)searchBar activate:(BOOL) active
   {
  self.theTableView.allowsSelection = !active;
  self.theTableView.scrollEnabled = !active;

   if (!active)
   {

    [disableViewOverlay removeFromSuperview];
    [searchBar resignFirstResponder];
  }
  else
  {
    self.disableViewOverlay.alpha = 0;
    [self.view addSubview:self.disableViewOverlay];

    [UIView beginAnimations:@"FadeIn" context:nil];
    [UIView setAnimationDuration:0.5];
    self.disableViewOverlay.alpha = 0.6;
    [UIView commitAnimations];

    // probably not needed if you have a details view since you
    // will go there on selection
    NSIndexPath *selected = [self.theTableView indexPathForSelectedRow];
    if (selected)
    {
        [self.theTableView deselectRowAtIndexPath:selected
                                         animated:NO];
    }
   }
    [searchBar setShowsCancelButton:active animated:YES];
   }



     -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
   {

   [self.view endEditing:YES];
   [self.theSearchBar resignFirstResponder];
   }
     -(BOOL)textFieldShouldReturn:(UITextField *)textField
   {
  textField.returnKeyType=UIReturnKeyDefault ;
  return[textField resignFirstResponder];
   }


 - (void)didReceiveMemoryWarning
  {
  [super didReceiveMemoryWarning];
   }

   #pragma mark - Table view data source

     - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
  return 1;
    }

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


    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
      (NSIndexPath *)indexPath
    {

     static NSString *CellIdentifier=@"Cell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier
      ];

     if(!cell)
     {


      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
     reuseIdentifier:CellIdentifier] ;
      }


      SmsTitle *title = [array objectAtIndex:indexPath.row];

     cell.textLabel.text = title.CategoryId;
      cell.textLabel.text = title.Title;
      cell.textLabel.text=title.Id;


         [cell.textLabel  setText:[NSString stringWithFormat:@"%@ ",[title 
     valueForKey:@"Title"]]];
     cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

     return cell;
      }

回答1:

Try this

searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 41.0)];
    [self.view addSubview:searchBar];
    searchBar.delegate=self;

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (isSearching) {
        return [filteredContentList count];
    }
    else {
        return [titlearray count];
    }
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableCell";

    SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    if (isSearching)
    {
        cell.nameLabel.text = [filteredContentList objectAtIndex:indexPath.row];
        cell.thumbnailImageView.image =[filteredImgArray objectAtIndex:indexPath.row];
    }
    else
    {
        cell.thumbnailImageView.image = [imagearray objectAtIndex:indexPath.row];
        cell.nameLabel.text = [titlearray objectAtIndex:indexPath.row];
    }
    return cell;
}
- (void)searchTableList {
    NSString *searchString = searchBar.text;

    for (int i=0; i<titlearray.count; i++) {
        NSString *tempStr=[titlearray objectAtIndex:i];
        NSComparisonResult result = [tempStr compare:searchString options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchString length])];
        if (result == NSOrderedSame)
        {
            [filteredContentList addObject:tempStr];
            [filteredImgArray addObject:[imagearray objectAtIndex:i]];
        }
    }

}

#pragma mark - Search Implementation

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    isSearching = YES;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    NSLog(@"Text change - %d",isSearching);

    //Remove all objects first.
    [filteredContentList removeAllObjects];
    [filteredImgArray removeAllObjects];

    if([searchText length] != 0) {
        isSearching = YES;
        [self searchTableList];
        //tblContentList.hidden=NO;
    }
    else {
        isSearching = NO;
       // tblContentList.hidden=YES;
    }
    [tblContentList reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"Cancel clicked");
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"Search Clicked");
    [self searchTableList];
}

I Hope it's help for you



回答2:

It doesn't work because you are always using this as a data source:

SmsTitle *title = [array objectAtIndex:indexPath.row];

So you never get data out of filteredContentList.

What you need to do is to keep reference to main UITableView in property and use this method to get propert NSArray as data source in all UITableViewDataSource delegate methods:

- (NSArray*) dataSourceForTableView:(UITableView*) tableView
{
    return tableView == self.tableView ? self.array : self.filteredContentList;
}


回答3:

View Did Load

allItem = [[NSArray alloc] initWithObjects:@"One",@"Two",@"Three",@"Four",@"Five",@"Six", nil];

displayItem = [[NSMutableArray alloc] initWithArray:allItem];

Add This Search Bar Method Only

-(void)searchBar:(UISearchBar *)    searchBar textDidChange:(NSString *)searchText

{
if ([searchText length] == 0)
{
    [displayItem removeAllObjects];
    [displayItem addObjectsFromArray:allItem];
}
else
{
    [displayItem removeAllObjects];

    for (NSString *string in allItem)
    {
        NSRange r = [string rangeOfString:searchText options:NSCaseInsensitiveSearch];

        if (r.location != NSNotFound)
        {
            [displayItem addObject:string];
        }
    }

}
[tableViewObj reloadData];

}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];}