2012-04-26 18 views
6

Quiero crear searchBar para mi tabla en el guión gráfico xcode, todo funciona para mí y no tengo ningún error, solo que la búsqueda no funciona.UISearchBar en el guión gráfico Xcode

Vi este tutorial pero aún no funciona. No puedo buscar mi tutorial:

-http://stackoverflow.com/questions/9897171/uisearchbar-implemented-with-storyboards 
    -http://www.youtube.com/watch?v=IqDZHgI_s24 

usted por favor me ayude, Gracias de antemano!

Aquí está mi código

CreateViewController.h

#import <UIKit/UIKit.h> 

@interface CreateViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource,  UISearchBarDelegate> 
{ 
// @property (weak, nonatomic) IBOutlet UISearchBar *searchBar; 
NSArray *datas; 
NSMutableArray *displayItems; 
IBOutlet UITableView * tableView; 
IBOutlet UISearchBar * searchbar; 
} 

@end 

CreateViewController.m

#import "CreateViewController.h" 

@interface CreateViewController() 

@end 

@implementation CreateViewController 

- (id)initWithStyle:(UITableViewStyle)style 
{ 
self = [super initWithStyle:style]; 
if (self) { 
    // Custom initialization 
} 
return self; 
} 

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 

datas = [NSMutableArray arrayWithObjects:@"Johan", @"Paul",@"George",@"Ringo", nil]; 
displayItems = [[NSMutableArray alloc] initWithArray:datas]; 
[super viewDidLoad]; 
} 

- (void)viewDidUnload 
{ 
[super viewDidUnload]; 
// Release any retained subviews of the main view. 
// e.g. self.myOutlet = nil; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
return (interfaceOrientation == UIInterfaceOrientationPortrait); 
} 

#pragma mark - Table view data source 

- (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. 
return [datas count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString *CellIdentifier = @"Cell";//This is the identifier in storyboard  
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if(!cell) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"]; 
} 

cell.textLabel.text = [datas objectAtIndex:indexPath.row]; 
return cell; 
} 
-(void)searchbar:(UISearchBar *)searchbar textDidChange:(NSString *)searchText{ 
if([searchText length] == 0){ 
    [displayItems removeAllObjects]; 
    [displayItems addObjectsFromArray:datas]; 
}else{ 
    [displayItems removeAllObjects]; 
    for(NSString * string in datas){ 
     NSRange r = [string rangeOfString:searchText options:NSCaseInsensitiveSearch]; 
     if (r.location != NSNotFound){ 
      [displayItems addObject:string]; 
     } 
    } 
} 
[tableView reloadData]; 
} 

#pragma mark - Table view delegate 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
// Navigation logic may go here. Create and push another view controller. 
/* 
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil]; 
// ... 
// Pass the selected object to the new view controller. 
[self.navigationController pushViewController:detailViewController animated:YES]; 
*/ 
} 

@end 

Respuesta

0

hacerlo de esta manera,

  • En el archivo de cabecera declarar matrices me gusta esto,

    NSMutableArray *datas; 
    NSMutableArray *displayItems; 
    
  • Luego cambie gama de inicialización en viewDidLoad como este,

    datas = [[NSMutableArray alloc] initWithObjects:@"Johan", @"Paul",@"George",@"Ringo", nil]; 
    displayItems = [[NSMutableArray alloc] initWithArray:datas]; 
    
  • Cambiar la matriz en cellForRowAt método,

    cell.textLabel.text = [displayItems objectAtIndex:indexPath.row]; 
    
  • A continuación, imprima su búsqueda cadena dentro de textDidChange método utilizando NSLog. Si no está imprimiendo, hay algo mal con la conexión IBOutlet. Si se imprime, reemplazar este método y ver si funciona,

    -(void)searchbar:(UISearchBar *)searchbar textDidChange:(NSString *)searchText{ 
    
    if([searchText length] == 0){ 
    
    }else{ 
        [displayItems removeAllObjects]; 
        for (int i=0; i<[datas count]; i++) { 
         if ([searchText hasPrefix:[datas objectAtIndex:i]]) { 
          [displayItems addObject:[datas objectAtIndex:i]]; 
         } else { 
    
         } 
        } 
    } 
    [tableView reloadData]; 
    } 
    

Mi método de clasificación no es la mejor del mundo. Pero intente que su código funcione.

Editar: Creo que su delegado no se activa. Pruebe este método en lugar de lo anterior.

- (void) searchBarSearchButtonClicked:(UISearchBar*) theSearchBar 
{ 
if([searchBar.text length] == 0){ 
arrayDisplayData = arrayOriginalData; 
}else{ 
    [arrayDisplayData removeAllObjects]; 
    for(NSString * string in arrayOriginalData){ 
     NSRange r = [string rangeOfString:searchBar.text options:NSCaseInsensitiveSearch]; 
     if (r.location != NSNotFound){ 
      [arrayDisplayData addObject:string]; 
     } 
    } 
} 
[tblResults reloadData]; 
} 

O esto,

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text 
+0

Gracias por su respuesta, pero todavía no funciona! –

+0

¿Su tabla muestra los datos que ha ingresado al iniciar la aplicación? Me refiero a esto, "datas = [NSMutableArray arrayWithObjects: @" Johan ", @" Paul ", @" George ", @" Ringo ", nada];" –

+0

sí, los muestra. –

0

necesita cambiar que cellForRowAtIndexPath utilizar la matriz displayItems en lugar de la matriz datas más

- (UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString *CellIdentifier = @"Cell";//This is the identifier in storyboard  
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if(!cell) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"]; 

} 

cell.textLabel.text = [displayItems objectAtIndex:indexPath.row]; 
return cell; 
} 

y también cambiar la numberOfRowsInSection utilizar la matriz displayItems contar

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 

// Return the number of rows in the section. 
return [displayItems count]; 
} 
+0

Gracias, pero Notthing sucedieron –

1

puede utilizar NSPredicate para esta función, modifique su método delegado de búsqueda de la siguiente manera

[datas release]; 
datas = nil; 

datas = [[NSMutableArray alloc] initWithArray: displayItems]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like[c] %@",[NSString stringWithFormat:@"%@*",searchBar.text]]; 
[datas filterUsingPredicate:predicate]; 
[tableView reloadData]; 

cheque el código de ejemplo aquí

http://dl.dropbox.com/u/58723521/SearchSample.zip

+0

tuve error en esta parte, searchBar.text] –

+0

voy a comprobar los enlaces gracias –

+0

u pudo haber utilizado alguna otra instancia UISearchBar, reemplace con ese nombre. – vishy

1

Estoy de acuerdo, tiene que cambiar su cellForRowAtIndexPath y numberOfRowsInSection a utilice la matriz displayItems en lugar de la matriz de datos. También verifique si ha configurado UISearchBarDelegate para su barra de búsqueda.

8

Usar este tutorial iOS Consejo rápido: Filtrado de una UITableView con una barra de búsqueda

http://code-ninja.org/blog/2012/01/08/ios-quick-tip-filtering-a-uitableview-with-a-search-bar/

-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text 
{ 
if(text.length == 0) 
{ 
    isFiltered = FALSE; 
} 
else 
{ 
    isFiltered = true; 
    filteredTableData = [[NSMutableArray alloc] init]; 

    for (Food* food in allTableData) 
    { 
     NSRange nameRange = [food.name rangeOfString:text options:NSCaseInsensitiveSearch]; 
     NSRange descriptionRange = [food.description rangeOfString:text options:NSCaseInsensitiveSearch]; 
     if(nameRange.location != NSNotFound || descriptionRange.location != NSNotFound) 
     { 
      [filteredTableData addObject:food]; 
     } 
    } 
} 

[self.tableView reloadData]; 
} 
+0

¿Qué sucede si tiene secciones en su tabla vista? ¿Cómo puede funcionar la búsqueda sabiendo que va a buscar dentro del contenido de las secciones en lugar de una sola matriz? – jaytrixz

+0

jaytrixz, puede encontrar mi otro tutorial sobre cómo filtrar un UITableView agrupado útil. Utiliza un diccionario de matrices en lugar de una única matriz. http://code-ninja.org/blog/2012/07/04/filtering-a-grouped-uitableview-with-a-search-bar/ –

Cuestiones relacionadas