Search code examples
iosiphoneuitableviewcell

Delete Cell from UITableViewCell?


I am faced with a small problem. I have a UIButton on my cell in which when pressed I want the cell to be deleted. I have attempted this, but gives error.

- (IBAction)deleteCell:(NSIndexPath *)indexPath {
MainViewController *view = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
[view.nameArray removeObjectAtIndex:indexPath.row];
[view.priceArray removeObjectAtIndex:indexPath.row];
[view.mainTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
}

I have a feeling I am not specifying the indexPath correctly, don't know how.

Any help is appreciated!


Solution

  • I would have done like this. I have my own MyCustomCell class where I have button for each cell.

    //MyCustomCell.h
    
    @protocol MyCustomCellDelegate <NSObject>
    
    -(void)deleteRecord:(UITableViewCell *)forSelectedCell;
    
    @end
    
    @interface MyCustomCell : UITableViewCell {
    
    }
    @property (nonatomic, strong) UIButton *deleteButton;
    @property (unsafe_unretained) id<MyCustomCellDelegate> delegate;
    @end
    
    //MyCustomCell.m
    
    - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
     {
        self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        if (self) {
         self.deleteButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 150, 44)];
        [self.deleteButton setTitle:@"Delete your record" forState:UIControlStateNormal];
        [self.deleteButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        [self.deleteButton addTarget:self action:@selector(editRecord:) forControlEvents:UIControlEventTouchUpInside];
        }
     }
    
    -(IBAction)editRecord:(id)sender {
        [self.delegate deleteRecord:self]; // Need to implement whoever is adopting this protocol
    }
    

    --

    // .h
    
    @interface MyView : UIView <UITableViewDataSource, UITableViewDelegate, MyCustomCellDelegate> {
    
    
    NSInteger rowOfTheCell;
    

    NOTE: Do not forget to set the delegate MyCustomCellDelegate to your cell.

    // .m
    
    -(void)deleteRecord:(UITableViewCell*)cellSelected
    {
         MyCustomCell *selectedCell = (MyCustomCell*)cellSelected;
         UITableView* table = (UITableView *)[selectedCell superview];
         NSIndexPath* pathOfTheCell = [table indexPathForCell:selectedCell]; //current indexPath
         rowOfTheCell = [pathOfTheCell row];  // current selection row
    
         [view.nameArray removeObjectAtIndex:rowOfTheCell];
         [view.priceArray removeObjectAtIndex:rowOfTheCell];
         [view.mainTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:pathOfTheCell]    withRowAnimation:UITableViewRowAnimationRight];
    }