how to add searchbar in uitableview?

前端 未结 4 896
轻奢々
轻奢々 2020-12-28 19:48

I have an NSMutableArray displayed in a UITableView, and I have added some elements there.

For example, element names are First, FirstTwo,

4条回答
  •  悲哀的现实
    2020-12-28 20:34

    If you are using search bar. then You can search your contain of table view using delegate method of searchbar

    (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
    {
    // myArray is main array for Table View
    // tempMainArray which store myArray Data
    
    myArray = [[NSMutableArray alloc]initWithArray:tempMainArray];
    NSMutableArray *searchArray = [[NSMutableArray alloc]init];
    
    
    [searchArray removeAllObjects];// remove all data that belongs to previous search
    if([searchText isEqualToString:@""]|| searchText==nil){
    
        [myArray removeAllObjects];
        myArray =  tempMainArray;
        [_objTableView reloadData];
    
        return;
    }
    
    NSInteger counter = 0;
    for(NSString *name in myArray)
    {
    
        NSRange r = [name rangeOfString:searchText];
        if(r.location != NSNotFound)
        {
            if(r.location== 0)//that is we are checking only the start of the names dynamicaly.
            {
                [searchArray addObject:name];
            }
        }
    
        counter++;
    
    
    }
    
    if (searchArray.count > 0) {
    
        [myArray removeAllObjects];
         myArray =  searchArray;
        [_objTableView reloadData];
    }
    else
    {
        [myArray removeAllObjects];
        myArray =  tempMainArray;
        [_objTableView reloadData];
    }
    
    }
    

提交回复
热议问题