Search code examples
iphoneobjective-ciosuitableviewsuperview

delete row with button in custom tableview cell


This is how the structure looks like.

--- UIView
   ---- ScrollView
       --- TableView

.

UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, -250, 320, 250)];

UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 70, 320, 150) style:UITableViewStylePlain];
    tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor blackColor];
    tableView.separatorStyle = normal;
    [tableView reloadData];

    [topView addSubview:tableView];

    [self.scrollView addSubview:topView];

In the tableview I am working with a custom tableview cell with a button in it. Here is the code for the button in my CellForRowAtIndex

[cell.btnDelete addTarget:self action:@selector(deleteAppointment:) forControlEvents:UIControlEventTouchUpInside];

Now to get the specific row I do this in my deleteAppointment

 UIButton *button = (UIButton *)sender;
    UITableViewCell *cell = (UITableViewCell *)button.superview;
    UITableView *tableView = (UITableView *)cell.superview;
    NSIndexPath *indexPath = [tableView indexPathForCell:cell];
    NSLog(@"row: %d",indexPath.row);

But it is still giving the following error.

-[ExceptionCell indexPathForCell:]: unrecognized selector sent to instance 0x210a2fa0

Can anyone help me?


Solution

  • its really Simple, in cellForRowAtIndexPath. just tag your button like

    cell.button.tag = indexPath.row;
    

    remove the value from array or dictionary (thats your dataSource) in button @selector method

    [array removeObjectAtIndex:button.tag];
    

    Now reload the tableView.

    [tableView reloadData];