UISearchBar cancel button issue

300 views Asked by At

in my app i have a sectioned and indexed tableview. i successfully managed to implement a UISearchBar to that tableview. it filters the table view when i start to type into the search box. however i could not be able to use Xcode's Cancel button properly. I need the cancel button to terminate the whole search(filter) process. when i hit cancel button it hides the keyboard and clears the search area but it does not refresh the tableview to its original state.(like the searchable in phone app in iPhones) i tried numerous things but no luck. here is how my code looks like:

can anyone tell me what i am missing? thanks a lot

#import "TableViewController.h"
#import "DetailViewController.h"
#import "Songs.h"

@implementation TableViewController

@synthesize allTableData;
@synthesize filteredTableData;
@synthesize letters;
@synthesize searchBar;
@synthesize isFiltered;

NSArray *SongsIndexTitles;

- (void)viewDidLoad {
    [super viewDidLoad];

    UIBarButtonItem *newButton = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    [[self navigationItem] setBackBarButtonItem:newButton];

    SongsIndexTitles = @[@"A", @"B", @"C",@"Ç", @"D", @"E", @"F", @"G", @"H", @"I",@"İ", @"J", @"K", @"L", @"M", @"N", @"O", @"Ö", @"P", @"R", @"S",@"Ş", @"T", @"U",@"Ü", @"V", @"Y", @"Z"];

    searchBar.delegate = (id)self;

    allTableData = [[NSArray alloc] initWithObjects:
                    [[Songs alloc] initWithName:@"Adam" andDescription:@"sanatcı 1"],
                    [[Songs alloc] initWithName:@"Anam" andDescription:@"sanatcı 2"],
                    [[Songs alloc] initWithName:@"Babam" andDescription:@"sanatcı 1"],
                    [[Songs alloc] initWithName:@"Burcu" andDescription:@"sanatcı 1"],
                    [[Songs alloc] initWithName:@"Cemil" andDescription:@"sanatcı 1"],
                    [[Songs alloc] initWithName:@"Cemal" andDescription:@"sanatcı 1"],
.
.
.
                    [[Songs alloc] initWithName:@"Yeşim" andDescription:@"sanatcı 1"],
                    [[Songs alloc] initWithName:@"Yaşar" andDescription:@"sanatcı 1"],
                    [[Songs alloc] initWithName:@"Ziya" andDescription:@"sanatcı 1"],
                    [[Songs alloc] initWithName:@"Ziban" andDescription:@"sanatcı 1"],

                    nil ];

    [self updateTableData:@""];
}

- (void)viewDidUnload
{
    [self setSearchBar:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

#pragma mark - Table view data source

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString* key = [letters objectAtIndex:section];
    return key;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return letters.count;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return SongsIndexTitles;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString* letter = [letters objectAtIndex:section];
    NSArray* arrayForLetter = (NSArray*)[filteredTableData objectForKey:letter];
    return arrayForLetter.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

    NSString* letter = [letters objectAtIndex:indexPath.section];
    NSArray* arrayForLetter = (NSArray*)[filteredTableData objectForKey:letter];
    Songs* songs = (Songs*)[arrayForLetter objectAtIndex:indexPath.row];

    cell.textLabel.text = songs.name;
    cell.detailTextLabel.text = songs.description;

    CGSize itemSize = CGSizeMake(50, 50);
    UIGraphicsBeginImageContextWithOptions(itemSize, NO, UIScreen.mainScreen.scale);
    CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
    [cell.imageView.image drawInRect:imageRect];
    cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return cell;

    return cell;
}

-(void)updateTableData:(NSString*)searchString
{
    filteredTableData = [[NSMutableDictionary alloc] init];

    for (Songs* songs in allTableData)
    {
        bool isMatch = false;
        if(searchString.length == 0)
        {
            isMatch = true;
        }
        else
        {
            NSRange nameRange = [songs.name rangeOfString:searchString options:NSCaseInsensitiveSearch];
            NSRange descriptionRange = [songs.description rangeOfString:searchString options:NSCaseInsensitiveSearch];
            if(nameRange.location != NSNotFound || descriptionRange.location != NSNotFound)
                isMatch = true;
        }

        if(isMatch)
        {
            NSString* firstLetter = [songs.name substringToIndex:1];

            NSMutableArray* arrayForLetter = (NSMutableArray*)[filteredTableData objectForKey:firstLetter];
            if(arrayForLetter == nil)
            {
                arrayForLetter = [[NSMutableArray alloc] init];
                [filteredTableData setValue:arrayForLetter forKey:firstLetter];
            }
                [arrayForLetter addObject:songs];
        }
    }
    letters = [[filteredTableData allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

    [self.tableView reloadData];
}

#pragma mark - Table view delegate

-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
    [self updateTableData:text];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    [self.searchBar setShowsCancelButton:YES animated:YES];
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    [self.searchBar setShowsCancelButton:NO animated:YES];
    return YES;
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    self.searchBar.text = nil;
    [self.searchBar resignFirstResponder];
    [self.tableView reloadData];
}


-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"ShowDetails"]) {
        DetailViewController *destinationViewController = segue.destinationViewController;

        UITableViewCell *selectedCell = [self.tableView cellForRowAtIndexPath:self.tableView.indexPathForSelectedRow];

        destinationViewController.title = selectedCell.textLabel.text;
    }
}

@end
1

There are 1 answers

2
rmaddy On BEST ANSWER

You need to reset your data source properly. Change this:

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    self.searchBar.text = nil;
    [self.searchBar resignFirstResponder];
    [self.tableView reloadData];
}

to:

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    self.searchBar.text = nil;
    [self.searchBar resignFirstResponder];
    [self updateTableData:@""];
}