2014-01-21 3 views
1

Мне нужно установить тег для кнопки, созданной на ячейке представления таблицы.
Я реализовал UISearchBar, и он хорошо работает.Проблема с тегом кнопки с UISearchBar

Проблема после фильтрации Tableview клетки, его indexpath.row изменения, как я устанавливаю
'button.tag = indexPath.row'.

Есть ли способ сохранить постоянное число строк для каждой ячейки?
Или есть ли другое решение?

Примечание: У меня есть несколько разделов в одном UITableView и isFiltered является булево значение, которое указывает пользователь начал набирать текст в UISearchBar.

Реализовано Поиск с помощью https://github.com/kwylez/IndexedTable

В cellForRowAtIndexPath:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *cellId = @"CheckBoxedCell"; 
    // NSString *cellId = [NSString stringWithFormat:@"Section:%d Row:%d",indexPath.section,indexPath.row]; 
    CheckBoxedCellClass *cell = (CheckBoxedCellClass *)[self.tableViewContact dequeueReusableCellWithIdentifier:cellId]; 

    if(!cell) 
    { 
     NSArray *nib; 
     if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) 
     { 
      nib = [[NSBundle mainBundle] loadNibNamed:@"CheckBoxedCellClass" owner:self options:nil]; 
     } 
     else if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
     { 
      nib = [[NSBundle mainBundle] loadNibNamed:@"CheckBoxedCellClass_iPad" owner:self options:nil]; 
     } 
      for (id object in nib) 
      { 
       if([object isKindOfClass:[CheckBoxedCellClass class]]) 
       { 
        cell = (CheckBoxedCellClass *)object; 
        break; 
       } 
      } 

      cell = [nib objectAtIndex:0]; 

    } 

     SaveCheckBoxedView *saveContact; 
     if(isFiltered == YES) 
     { 
      saveContact = [filterdArray objectAtIndex:indexPath.row]; 
      cell.nameLabel.text = saveContact.nameString; 
     } 
     else 
     { 
      saveContact = [mutableArray objectAtIndex:indexPath.row]; 
      cell.nameLabel.text = [[objectsForCharacters objectForKey:[arrayOfCharacters objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row]; 
     } 

     //cell.nameLabel.text = saveContact.nameString; 

     cell.companyLabel.text = saveContact.companyString; 
     cell.invIdLabel.text = [NSString stringWithFormat:@"%d", saveContact.invitId]; 

     //set fonts 
     if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) 
     { 

      [cell.companyLabel setFont:[UIFont italicSystemFontOfSize:10.0]]; 
     } 
     else 
     { 

      [cell.companyLabel setFont:[UIFont italicSystemFontOfSize:14.0]]; 
     } 



    //handling check box 

    NSInteger rowNumber = 0; 
    for(NSInteger i = 0; i < indexPath.section ; i++) 
    { 
     rowNumber += [self tableView:self.tableViewContact numberOfRowsInSection:i]; 
    } 

    rowNumber += indexPath.row; 

    /*if([indexPath compare:self.lastIndexPath] == NSOrderedSame) 
    { 
     cell.accessoryType = UITableViewCellAccessoryCheckmark; 
     NSString *finalIntId = [mutableArrayOfIds objectAtIndex:rowNumber]; 
     NSLog(@"Tagged checked button id = %@", finalIntId); 
     [arrayOfIds addObject:finalIntId]; 
    }*/ 

    UIButton *checkBox; 
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) 
    { 
     checkBox = [[UIButton alloc]initWithFrame:CGRectMake(7, 8, 30, 30)]; 
    } 
    else 
    { 
     checkBox = [[UIButton alloc]initWithFrame:CGRectMake(15, 13, 30, 30)]; 
    } 

    [checkBox setImage:[UIImage imageNamed:@"checkBox.png"] forState:UIControlStateNormal]; 
    [checkBox addTarget:self action:@selector(checkBoxClicked:event:) forControlEvents:UIControlEventTouchUpInside]; 
    if(isFiltered == YES) 
    { 
     checkBox.tag = ; 
    } 
    else 
    { 
     checkBox.tag = rowNumber; 
    } 
    [cell.contentView addSubview:checkBox]; 

    return cell; 
} 
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { 
    if(isFiltered == YES) { 
     return Nil; 
    } else { 
     NSArray *toBeReturned = [NSArray arrayWithArray: 
           [@"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|#" 
            componentsSeparatedByString:@"|"]]; 
     return toBeReturned; 
    } 
} 

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { 
    if (title == UITableViewIndexSearch) { 
     CGRect searchBarFrame = self.searchDisplayController.searchBar.frame; 
     [tableView scrollRectToVisible:searchBarFrame animated:YES]; 

     return -1; 
    } else { 
     NSInteger count = 0; 

     for (NSString *character in arrayOfCharacters) { 
      if ([character isEqualToString:title]) { 
       return count; 
      } 
      count ++; 
     } 
     return 0; 
    } 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    if(isFiltered == YES) { 
     return 1; 
    } else { 
     return [arrayOfCharacters count]; 
     //return 1; 
    } 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    if(isFiltered == YES) { 
     return [filterdArray count]; 
    } else { 
     //return [mutableArray count]; 
     return [[objectsForCharacters objectForKey:[arrayOfCharacters objectAtIndex:section]] count]; 
    } 
} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    if ([arrayOfCharacters count] == 0) { 
     return @""; 
    } 

    return [NSString stringWithFormat:@"%@", [arrayOfCharacters objectAtIndex:section]]; 
} 

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText 
{ 
    if(searchText.length == 0) 
    { 
     isFiltered = NO; 
    } 
    else 
    { 
     isFiltered = YES; 
     filterdArray = [[NSMutableArray alloc] init]; 
     for (SaveCheckBoxedView *contact in mutableArray) 
     { 
      NSRange nameRange = [contact.nameString rangeOfString:searchText options:NSCaseInsensitiveSearch]; 
      if(nameRange.location != NSNotFound) 
      { 
       [filterdArray addObject:contact]; 
      } 
     } 
    } 
    [self.tableViewContact reloadData]; 
} 

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString 
{ 
    [filterdArray removeAllObjects]; 
    if(searchString.length > 0) 
    { 
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [search] %@", self.mySearchBar.text]; 
     for (NSString *key in arrayOfCharacters) 
     { 
      NSArray *matches = [objectsForCharacters[key] filteredArrayUsingPredicate:predicate]; 
      [filterdArray addObjectsFromArray:matches]; 
     } 
    } 
    return YES; 
} 
+0

Вопрос не ясен. Вы хотите, чтобы тег кнопки был таким же, как и до фильтрации? Может ли опубликовать полный метод cellForRowAtIndexPath? – Rashad

+0

@Rashad Я добавил весь метод cellForRowAtIndexPath –

+0

Что вам нужно? Тег кнопки останется таким же даже после фильтрации? – Rashad

ответ

0

Я описываю один из способов сделать это, вы можете найти лучший путь.

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString 
{ 
    [filterdArray removeAllObjects]; 
    if(searchString.length > 0) 
    { 
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [search] %@", self.mySearchBar.text]; 
     for (NSString *key in arrayOfCharacters) 
     { 
      NSArray *matches = [objectsForCharacters[key] filteredArrayUsingPredicate:predicate]; 
      /****see bellow****/ 
      [filterdArray addObjectsFromArray:matches]; 
     } 
    } 
    return YES; 
} 

Постарайтесь найти номер строки каждого объекта из «совпадений». это будет тег ваших кнопок. Сделайте filterdArray массив словаря. Добавьте 2 слова в словарь. один для тега другой для значения. in cellForRowAtIndexPath.

if(isFiltered == YES) 
{ 
    checkBox.tag = [filterdArray objectForKey: @"tag"] ; 
} 
else 
{ 
    checkBox.tag = rowNumber; 
} 
Смежные вопросы