2017-02-20 5 views
0

У меня есть UIButton в UITableViewCell. Когда вызывается UIButton, я сохраняю тег кнопки нажатого в массиве. Поэтому, когда я ищу в UITableView, используя UISearchController, я получаю желаемый результат, но выбранная кнопка выбрана в неправильной ячейке.Выбор кнопки просмотра стола неправильный после поиска

Pic 1 - Кнопка выбрана и до поиска

enter image description here

рис 2 - После поиска enter image description here

В ПОС 1, я выбрал кнопку, которая принадлежит "номер 1" , но после поиска, как вы можете видеть на рис. 2, выход правильный, но кнопки не следует выбирать. Как решить эту проблему?

---- Отредактированный ---- Реализация

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    if (shouldShowSearchresult) { 
    return searchArray.count; 
    } 
    else 
    { 
    return roomNameArray.count; 
    } 

} 
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *cellIdentifier = @"roomCells"; 
    cell = (roomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
    if (shouldShowSearchresult) { 
    cell.roomName.text = [searchArray objectAtIndex:indexPath.row]; 
    // cell.seatingCapacity.text = [NSString stringWithFormat:@"Seats %@ people",[seatingCapacityArray objectAtIndex:indexPath.row]]; 
    cell.approval.text = @"Approval not required"; 
    } 
    else 
    { 
    cell.roomName.text = [roomNameArray objectAtIndex:indexPath.row]; 
    // cell.seatingCapacity.text = [NSString stringWithFormat:@"Seats %@ people",[seatingCapacityArray objectAtIndex:indexPath.row]]; 
    cell.approval.text = @"Approval not required"; 

    } 

    for (UIButton *slotButton in cell.timeslotScrollView.subviews) { 
     [slotButton removeFromSuperview]; 
    } 
    UIButton *slotButton; 
    cell.timeslotScrollView.contentSize = CGSizeMake(500, 0); 
    cell.timeslotScrollView.scrollEnabled = YES; 
    cell.timeslotScrollView.showsHorizontalScrollIndicator = NO; 
    int buttonSpace = 10; 
    int buttonWidth = 68; 
    int buttonHeight = 35; 
    int yPosition = 0; 
    float xPosition = 0; 



    for (int i=0; i<timeSlotArray.count; i++) { 
     slotButton = [[UIButton alloc]init]; 
     slotButton.frame = CGRectMake(xPosition, yPosition, buttonWidth, buttonHeight); 
     [slotButton setTitle:[NSString stringWithFormat:@"%@", timeSlotArray[i]] forState:UIControlStateNormal]; 
     [slotButton setTitleColor:[UIColor colorWithRed:0.23 green:0.71 blue:0.29 alpha:1.0] forState:UIControlStateNormal] ; 
     slotButton.layer.borderWidth = 2; 
     slotButton.layer.borderColor = [UIColor colorWithRed:0.23 green:0.71 blue:0.29 alpha:1.0].CGColor; 
     slotButton.layer.cornerRadius = 3; 
     slotButton.tag = i; 



     slotButton.userInteractionEnabled = YES; 
     [slotButton addTarget:self action:@selector(didTap:) forControlEvents:UIControlEventTouchUpInside]; 
     xPosition = slotButton.frame.origin.x+buttonWidth+buttonSpace; 



     if (cell.timeslotScrollView.subviews.count < timeSlotArray.count) 
     { 
     [cell.timeslotScrollView addSubview:slotButton]; 
     } 

    } 

    NSArray *tempArray = cell.timeslotScrollView.subviews; 
    NSLog(@"%ld",tempArray.count); 

    return cell; 
} 

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cello forRowAtIndexPath:(NSIndexPath *)indexPath{ 


    if (indexPath.row==tappedButtonRowIndex) 
    { 

    for (int i = 0; i <cell.timeslotScrollView.subviews.count; i++) 
    { 
     UIView *view = [cell.timeslotScrollView.subviews objectAtIndex:i]; 
     if ([view isKindOfClass:[UIButton class]]) 
     { 
     UIButton *slotTempBtn = (UIButton *)view; 
     BOOL btnFound = false; 
     for (NSString *index in buttonSelectedArray) 
     { 
      if ([index integerValue]== slotTempBtn.tag) 
      { 
      btnFound = true; 
      break; 
      } 
     } 
     if (btnFound) { 
      [slotTempBtn setBackgroundColor:[UIColor greenColor]]; 
     } 
     else 
     { 
      [slotTempBtn setBackgroundColor:[UIColor whiteColor]]; 
     } 
     } 

    } 
    } 
    else 
    { 
    for (UIView *view in cell.timeslotScrollView.subviews) 
    { 
     if ([view isKindOfClass:[UIButton class]]) 
     { 
     UIButton *slotTempBtn = (UIButton *)view; 
     [slotTempBtn setBackgroundColor:[UIColor whiteColor]]; 
     } 
    } 
    } 




    cell.slotButtonDelegate=self; 

} 

Поиск Реализация

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController 
{ 
    [self updateFilteredContentWithSearchText:searchController.searchBar.text]; 

    [_roomTableView reloadData]; 
} 

- (void)updateFilteredContentWithSearchText:(NSString*)searchText 
{ 
    [searchArray removeAllObjects]; 
    for (NSString *room in roomNameArray) 
    { 
    NSRange nameRange = [room rangeOfString:searchText options:NSCaseInsensitiveSearch]; 
    if (nameRange.location != NSNotFound) 
    { 
     [searchArray addObject:room]; 
    } 
    } 
    self.roomTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero]; 
} 

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText 
{ 
    if (searchBar.text.length >= 1) { 
    shouldShowSearchresult = true; 
    } 
    else 
    { 
    shouldShowSearchresult = false; 
    } 
    [_roomTableView reloadData]; 

} 

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar 
{ 
    shouldShowSearchresult = false; 
    [_roomTableView reloadData]; 
} 
+0

Пожалуйста, добавьте свой код реализации и код создания ячейки таблицы. – Priyal

+0

Любые идеи? – user3310076

ответ

0

Как TableView клетка повторно здесь необходимо сделать одно условие и проверить там, если условие true, тогда кнопка выбирается в противном случае, кнопка является нормальной, поэтому, когда ячейка следующего времени будет повторно использоваться, она будет отображаться надлежащим образом по данным массива. проверьте состояние в своем tableView cellForRow method

if yourArray.count > 0 { 
    //check your array and set cell's button selection as per id or tag 
} 
else { 
    //set all cells all the button unselected 
} 
Смежные вопросы