Dridia
Dridia

Reputation: 183

Delete selected cells from UITableView

I would like to delete all the selected cell from when i swipe left.

My .m file

- (IBAction)handleSwipeLeft:(UISwipeGestureRecognizer *)sender{

    CGPoint location = [_gestureSwipeLeft locationInView:_tblThingsToDo];
    NSIndexPath *swipedIndexPath = [_tblThingsToDo indexPathForRowAtPoint:location];
    UITableViewCell *swipedCell  = [_tblThingsToDo cellForRowAtIndexPath:swipedIndexPath];

    if (swipedCell.selected == NO) {
        swipedCell.selected = YES;
    }
    else{
    swipedCell.selected = NO;
    }
}


-(void)deleteCurrentobject:(id)sender{
    if(self.selectedCells){
        [_things removeObjectAtIndex:_indexPath.row];
        [self.tblThingsToDo deleteRowsAtIndexPaths:[NSArray arrayWithObject:_indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

I want all the swipedCell.selected to be deleted when pressing on the button that calls the deleteCurrentObject method. How am i going to do that?

Upvotes: 0

Views: 143

Answers (2)

Tirth
Tirth

Reputation: 7789

Place below line stuff inside init method of swipedCell class otherwise swipedCell object creation time.

[self addObserver: swipedCell forKeyPath:@"selected" options:NSKeyValueObservingOptionNew context:NULL];

When you handleSwipeLeft: method called it will automatically call below method,

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
     if ([keyPath isEqualToString:@"selected"] && [object isKindOfClass:[UITableViewCell class]]) {
       if(object.selected){
       [_things removeObjectAtIndex:_indexPath.row];
         [self.tblThingsToDo beginUpdates];
         [self.tblThingsToDo deleteRowsAtIndexPaths:[NSArray arrayWithObject:_indexPath] withRowAnimation:UITableViewRowAnimationFade];
         [self.tblThingsToDo endUpdates];
      }
    }
}

On remove observer use below code stuff

[self removeObserver:swipedCell forKeyPath:@"selected"];

Upvotes: 1

Akhilrajtr
Akhilrajtr

Reputation: 5182

Try this,

- (IBAction)handleSwipeLeft:(UISwipeGestureRecognizer *)sender{

    CGPoint location = [_gestureSwipeLeft locationInView:_tblThingsToDo];
    NSIndexPath *swipedIndexPath = [_tblThingsToDo indexPathForRowAtPoint:location];
    _indexPath = swipedIndexPath;
    UITableViewCell *swipedCell  = [_tblThingsToDo cellForRowAtIndexPath:swipedIndexPath];

    if (swipedCell.selected == NO) {
        swipedCell.selected = YES;
    } else{
        swipedCell.selected = NO;
    }
}


-(void)deleteCurrentobject:(id)sender{
     if(self.selectedCells){
         [_things removeObjectAtIndex:_indexPath.row];
         [self.tblThingsToDo beginUpdates];
         [self.tblThingsToDo deleteRowsAtIndexPaths:[NSArray arrayWithObject:_indexPath] withRowAnimation:UITableViewRowAnimationFade];
         [self.tblThingsToDo endUpdates];
     }
}

Upvotes: 0

Related Questions