2011-04-04 17 views
12

Tengo NSMutableArray en un UITableView, y he agregado algunos elementos allí.cómo agregar barra de búsqueda en uitableview?

Por ejemplo, los nombres de los elementos son Primero, Primero, Segundo, Segundo, Segundo, Tercero, Dos.

Ahora quiero agregar una barra de búsqueda en la pantalla. En esa barra de búsqueda cuando escribo F, la tabla solo debe mostrar Primero y Primero dos.

¿Cómo debo hacer esto?

+0

Puede utilizar UISearchController lugar. https://www.raywenderlich.com/113772/uisearchcontroller-tutorial – PrafulD

Respuesta

17

La mejor manera de familiarizarse con esto es siguiendo un tutorial over here over here. La parte que busca, es la siguiente:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText 
{ 
    [tableData removeAllObjects];// remove all data that belongs to previous search 
    if([searchText isEqualToString:@""]searchText==nil){ 
     [myTableView reloadData]; 
     return; 
    } 

    NSInteger counter = 0; 
    for(NSString *name in dataSource) 
    { 
     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init]; 
     NSRange r = [name rangeOfString:searchText]; 
     if(r.location != NSNotFound) 
     { 
     if(r.location== 0)//that is we are checking only the start of the names. 
     { 
      [tableData addObject:name]; 
     } 
     } 

     counter++; 
     [pool release]; 

    } 

    [myTableView reloadData]; 
} 
+12

+1 para dejar el código porque su enlace ha muerto. –

+1

Agregó un nuevo enlace. – Joetjah

+0

Quiero datos del servicio web. ¿Puedo usar el mismo código? Gracias por el enlace. –

27
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; 

searchBar.delegate = self; 

self.tableView.tableHeaderView = searchBar; 
0

lo hice yo mismo y está trabajando absolutamente bien.

Declare dos matrices mutables. Uno que contiene todos los datos y el segundo para almacenar los datos filtrados. Aquí el usuario de búsqueda es la barra de búsqueda. aray es una matriz principal que almacena todos los datos. establecer la propiedad de mayúsculas de la barra de búsqueda en la oración para que funcione correctamente.

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText 
{ 
    [searchuser.text lowercaseString]); 
    filteredarray=[[NSMutableArray alloc]init]; 
    int l=(int)[searchuser.text length]; 
    if (l>0) 
    { 
     NSMutableString * data=[[NSMutableString alloc]init]; 
     int a=(int)[aray count]; 

     for (int i=0;i<=a-1;i++) 
     { 
      data=[aray objectAtIndex:i]; 
      if ([searchuser.text isEqualToString:data]) 
      { 
       [filteredarray addObject:data]; 
      } 
      if ([data length]>l) 
      { 
       NSMutableString * string=[[NSMutableString alloc]initWithString:[data substringWithRange:NSMakeRange(0, l)]]; 

       if ([searchuser.text isEqualToString:string]) 
       { 
        [filteredarray addObject:data]; 

       } 
      } 
     } 
    } 
    else 
    { 
     filteredarray=aray; 
    } 
    [tableview reloadData]; 
} 
1

Si está utilizando la barra de búsqueda. A continuación, puede buscar su contienen de vista de la tabla utilizando el método delegado de barra de búsqueda

(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]; 
} 

} 
Cuestiones relacionadas