2017-01-09 4 views
0

Я сделал один образец демо. Как и выбранная печать ячейки после нажатия кнопки «Готово». Он работает нормально.Как удалить данные из массива, когда снимите ячейку в UITableview?

Кодекс

@synthesize arrayContainer,filteredRecipes,myTableView,filtered,selectedRaw; 


- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
    self.arrayContainer = [[NSMutableArray alloc]initWithObjects:@"One",@"Two",@"Three",@"Four",@"Five",@"Six",@"Seven",@"Eight",@"Nine", nil]; 
    self.selectedRaw = [[NSMutableArray alloc]init]; 

} 

-(IBAction)printSelectedItem:(id)sender 
{ 
    NSLog(@"The Selected Items are %@",self.selectedRaw); 
} 
- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    if(filtered == YES) 
    { 
     return self.filteredRecipes.count; 

    } 
    else 
    { 
     return self.arrayContainer.count; 

    } 
} 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *identifier = @"myCell"; 

    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:identifier]; 

    if(filtered == YES) 
    { 
     cell.textLabel.text = [self.filteredRecipes objectAtIndex:indexPath.row]; 

    } 
    else 
    { 
     cell.textLabel.text = [self.arrayContainer objectAtIndex:indexPath.row]; 

    } 


    return cell; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{ 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 


    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) { 

     cell.accessoryType = UITableViewCellAccessoryNone; 
     // NSString *string = [self.selectedRaw objectAtIndex:indexPath.row]; 

     [self.selectedRaw removeObjectAtIndex:indexPath.row]; 

    } else { 

     cell.accessoryType = UITableViewCellAccessoryCheckmark; 
     NSString *temp = [self.arrayContainer objectAtIndex:indexPath.row]; 
     [self.selectedRaw addObject:temp]; 
    } 

} 

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar 
{ 

    [searchBar setShowsCancelButton:YES animated:YES]; 
} 


-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText 
{ 

    if([searchText length] == 0) 
    { 
     self.filtered = NO; 
    } 
    else 
    { 
     self.filtered = YES; 

     self.filteredRecipes = [[NSArray alloc]init]; 

     NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@",searchText]; 

     filteredRecipes = [self.arrayContainer filteredArrayUsingPredicate:resultPredicate]; 
    } 

    [self.myTableView reloadData]; 
} 

Вопрос

-> При печати выбранной строки зрения таблицы, отображается в журнале отлично.

-> Но когда я снял выбранные элементы, это дает мне ошибку.

Пожалуйста, дайте мне решение.

Другой вопрос: когда я искал конкретный элемент (выбранный), он дает мне выбранный элемент отлично, затем я отменю выбор после того, как я отменил поиск, тогда он дает мне снова выбранный элемент, который я снял ранее.

Выход изображения

enter image description here

выбран Raw

enter image description here

Переполнение второго сырья

enter image description here

enter image description here

enter image description here

+0

Для выходного изображения сначала я снял третью строчку, затем я снял флажок. – hd1344

+0

, потому что содержимое вашего массива не совпадает с вашим представлением (количество строк, поэтому вы не должны использовать indexpath.row в качестве основы для удаления объекта по индексу). – Joshua

+0

Если я не ошибаюсь, вы хотите отменить выделение конкретной ячейки когда вы нажимаете на него во второй раз ?? .... – Developer

ответ

2

Поэтому, пожалуйста, попробуйте это.

#import "SecondViewController.h" 

@interface SecondViewController() 
@property(nonatomic,strong)NSArray *arrayContainer; 
@property(nonatomic,strong)NSArray *filteredRecipes; 
@property(nonatomic,strong)NSMutableArray *selectedRaw; 
@property(nonatomic,assign)BOOL filtered; 
@end 

@implementation SecondViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    _arrayContainer = @[@"One",@"Two",@"Three",@"Four"]; 
//  _arrayContainer = [[NSMutableArray alloc]initWithArray:]; 
    _selectedRaw = [[NSMutableArray alloc]init]; 
    [self.tableView reloadData]; 
    // Do any additional setup after loading the view. 
} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

/* 
#pragma mark - Navigation 

// In a storyboard-based application, you will often want to do a little preparation before navigation 
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
    // Get the new view controller using [segue destinationViewController]. 
    // Pass the selected object to the new view controller. 
} 
*/ 

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 
    return 1; 
} 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
    if(_filtered) 
     return _filteredRecipes.count; 
    else 
     return _arrayContainer.count; 
} 

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 

    if(_filtered){ 
     NSString *tmp = [_filteredRecipes objectAtIndex:indexPath.row]; 
     cell.textLabel.text = tmp; 
     if([_selectedRaw containsObject:tmp]) 
      cell.accessoryType = UITableViewCellAccessoryCheckmark; 
     else 
      cell.accessoryType = UITableViewCellAccessoryNone; 
    }else{ 
     NSString *tmp = [_arrayContainer objectAtIndex:indexPath.row]; 
     cell.textLabel.text = tmp; 
     if([_selectedRaw containsObject:tmp]) 
      cell.accessoryType = UITableViewCellAccessoryCheckmark; 
     else 
      cell.accessoryType = UITableViewCellAccessoryNone; 
    } 
    return cell; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{ 

    if(self.filtered){ 
     if([self.selectedRaw containsObject:[self.filteredRecipes objectAtIndex:indexPath.row]]){ 
      [self.selectedRaw removeObjectAtIndex:[self.selectedRaw indexOfObject:[self.filteredRecipes objectAtIndex:indexPath.row]]]; 
     }else{ 
      NSString *temp = [self.filteredRecipes objectAtIndex:indexPath.row]; 
      [self.selectedRaw addObject:temp]; 
     } 
    }else{ 
     if([self.selectedRaw containsObject:[self.arrayContainer objectAtIndex:indexPath.row]]){ 
      [self.selectedRaw removeObjectAtIndex:[self.selectedRaw indexOfObject:[self.arrayContainer objectAtIndex:indexPath.row]]]; 
     }else{ 
      NSString *temp = [self.arrayContainer objectAtIndex:indexPath.row]; 
      [self.selectedRaw addObject:temp]; 
     } 
    } 
    [self.tableView reloadData]; 

} 

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{ 
    if([searchText length] == 0) 
    { 
     self.filtered = NO; 
    } 
    else 
    { 
     self.filtered = YES; 


     NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@",searchText]; 

     _filteredRecipes = [self.arrayContainer filteredArrayUsingPredicate:resultPredicate]; 
    } 

    [self.tableView reloadData]; 
} 

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{ 
    _filtered = !_filtered; 
} 

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{ 
    _filtered = !_filtered; 
} 

@end 
+0

Извините, это была орфографическая ошибка ... – Gulliva

+0

Куда мне помещать, я путаю – hd1344

+0

Замените это в методе tableView didSelectRowAtIndexPath ... Я работаю над весь код. Дайте мне минутку ... Но, по крайней мере, это должно помочь вам – Gulliva

0

1: Вы должны принять массив со словарем с параметром как

[{ 
    value : “One”, 
    state : “Check” 
    }, 
    { 
    value : “Two”, 
    state : “UnCheck” 
    } 
    ] 

затем на cellForRowAtindexParth

if (self.selectedRaw[indexPath.row] as !  NSDictionary).value(forKey:”state”) as! String == “Check”{ 
    //change to check mark 
    } 
    else{ 
    //change to UnCheck mark 
    } 

В DidSelectRowAtIndexPath

if (cell.accessoryType == UITableViewCellAccessoryCheckmark) { 

if (arr[indexPath.row] as ! NSDictionary).value(forKey:”state”) as!   String == “Check”{ 
    //change state value to UnCheck 
}else{ 
    //change state value to Check 
    } 

    } 

2: На втором этапе вы должны сделать ту же работу

+0

@Amait: -Я уже сделал то, что вы отправляете. Вывод вроде: Two, «", Four, Один – hd1344

+0

Он дает мне "", На месте где я не проверю содержимое ячейки. Спасибо – hd1344

+0

возьмите массив, в котором вы можете сохранить словарь с двумя параметрами firstValue и вторым состоянием для exp. value = One, state = check, то вы можете легко сделать это –

1

Вы должны удалить данные, основанные на Object не основаны на Index так здесь вы можете пойти с ниже код:

первый вы должны проверить состояние фильтра в методе didselect

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{ 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 


    if(filtered == YES) 
     { 
      if (cell.accessoryType == UITableViewCellAccessoryCheckmark) { 

      cell.accessoryType = UITableViewCellAccessoryNone; 
      [self.selectedRaw removeObject:[self.filteredRecipes objectAtIndex:indexPath.row]]; 

      } else { 

      cell.accessoryType = UITableViewCellAccessoryCheckmark; 
      [self.selectedRaw addObject:[self.filteredRecipes objectAtIndex:indexPath.row]] 
      } 


    } 
    else 
    { 
     if (cell.accessoryType == UITableViewCellAccessoryCheckmark) { 

      cell.accessoryType = UITableViewCellAccessoryNone; 

      [self.selectedRaw removeObject:[self.arrayContainer objectAtIndex:indexPath.row]]; 

     } else { 

      cell.accessoryType = UITableViewCellAccessoryCheckmark; 
      [self.selectedRaw addObject:[self.arrayContainer objectAtIndex:indexPath.row]] 
     } 

    } 
} 

2-е Решение проблемы:

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

    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:identifier]; 

    if(filtered == YES) 
    { 
     cell.textLabel.text = [self.filteredRecipes objectAtIndex:indexPath.row]; 
     if([selectedRaw containsObject:self.filteredRecipes[indexPath.row]]){ 
      cell.accessoryType = UITableViewCellAccessoryCheckmark; 
     }else{ 
      cell.accessoryType = UITableViewCellAccessoryNone; 
     } 

    } 
    else 
    { 
     cell.textLabel.text = [self.arrayContainer objectAtIndex:indexPath.row]; 
     if([selectedRaw containsObject:self.arrayContainer[indexPath.row]]){ 
      cell.accessoryType = UITableViewCellAccessoryCheckmark; 
     }else{ 
      cell.accessoryType = UITableViewCellAccessoryNone; 
     } 

    } 


    return cell; 
} 

Надежда Это поможет вам.

+0

: -Спасибо, моя первая проблема решена. Спасибо, можете предложить мне вторую проблему? – hd1344

+0

Но я думаю, что ваша проблема f2nd связана с первой, и она автоматически разрешится, если вы проверите ее правильно? – CodeChanger

+0

Не нужно ставить код if (filter == YES), просто поместите только код детали только, работая отлично. Спасибо – hd1344

Смежные вопросы