6
votes

Uiseearchbar dans Storyboard Xcode

Je veux créer une barre de recherche pour ma table dans Storyboard Xcode, tout fonctionne pour moi et je n'ai aucune erreur, juste la recherche ne fonctionne pas.

J'ai vu ce tutoriel mais je ne travaille toujours pas. Je ne peux pas chercher. mon tutoriel: p> xxx pré>

voudriez-vous m'aider, s'il vous plaît, aidez-moi, Merci d'avance! P>

Voici mon code P>

CreativeViewController.h p> xxx pré>

CreativeViewController.m P>

#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


0 commentaires

5 Réponses :


0
votes

Faites-le comme ça,

  • dans votre fichier d'en-tête déclarer des tableaux comme celui-ci, P>

    - (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
    
  • puis modifier la matrice d'initialisation dans ViewDidLoadload forte> comme ceci, p>

    - (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];
    }
    
  • Changer le tableau dans Cellfroworat Strong> Méthode, P>

    -(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];
    }
    
  • Puis imprimez votre chaîne de recherche à l'intérieur TEXTDIDCHANGE STRAR> à l'aide de NSLOG. S'il ne s'agit pas d'impression, il y a quelque chose qui ne va pas avec la connexion Iboutlet. Si elle imprime, remplacez cette méthode et voyez si cela fonctionne, P>

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


2 commentaires

Votre TableView affiche-t-elle les données que vous avez posées lorsque vous démarrez l'application? Je veux dire celles-ci, "Datas = [NsmutableArraRay ArraywithObjects: @" Johan ", @" Paul ", @" George ", @" Ringo ", Nil];"


@deamonsarea merci, je l'essaie que le second ne fonctionnait pas et je n'ai pas travaillé dans la barre de recherche d'erreur.text and [tbloaddata];



0
votes

Vous devez modifier votre charophrowortindexpath pour utiliser le tableau displayItems plutôt que le tableau de données

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

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


1 commentaires

Merci, mais rien ne s'est passé



1
votes

Vous pouvez utiliser Nspredicate pour cette fonction, modifier la méthode de votre déléguée de recherche comme ci-dessous xxx

vérifier le code d'échantillon ici

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


1 commentaires

Vous auriez peut-être utilisé une autre instance UiseearchBar, remplacez-le avec ce nom.



1
votes

Je suis d'accord, vous devez modifier votre cellfrowrowindexpath et numérosofrowsection pour utiliser le tableau gra-à-la-ci plutôt que le tableau de données. Vérifiez également si vous avez défini le UisearchBelegate pour votre barre de recherche.


0 commentaires

8
votes

Utilisez ce tutoriel IOS Astuce rapide: filtrage d'une vision utile avec une barre de recherche

http://code-ninja.org/blog/2012/01/08/IOS-Quick-tip-filtering-a-ittableview-with-search -Bar / xxx


2 commentaires

Et si vous avez des sections dans votre TableView? Comment rechercher des travaux de savoir que vous allez chercher à l'intérieur du contenu des sections au lieu d'un seul tableau?


Jaytrixz, vous trouverez peut-être mon autre didacticiel sur le filtrage d'une vision de l'utable groupée utile. Il utilise un dictionnaire de tableaux au lieu d'un seul tableau. Code-Ninja .org / blog / 2012/07/04 / ...