2015-06-09 2 views
0

В моем приложении у меня есть разделенное и индексированное представление таблицы. Мне удалось реализовать UISearchBar для этого табличного представления. он фильтрует представление таблицы, когда я начинаю вводить текст в поле поиска. однако я не смог правильно использовать кнопку «Отмена» Xcode. Мне нужна кнопка отмены, чтобы завершить весь процесс поиска (фильтра). когда я нажимаю кнопку отмены, он скрывает клавиатуру и очищает область поиска, но не обновляет представление таблицы до его исходного состояния (например, поиск в приложении для телефона в iPhone). Я пробовал много вещей, но не повезло. вот как выглядит мой код:UISearchBar cancel button issue

может ли кто-нибудь сказать мне, что мне не хватает? большое спасибо

#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 

ответ

0

Необходимо правильно восстановить исходный код. Изменить это:

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

к:

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

вы более удивительным :) –

+1

Не забудьте выбрать этот ответ как правильный один и вверх-голосования (нажмите на треугольник над номером к оставил). Многие люди отвечают на вопросы здесь, чтобы улучшить их репутацию SO, и именно так вы помогаете им это делать. –