使用自定义tableview单元格中的按钮删除行

Ste*_*ann 0 iphone objective-c uitableview superview ios

这就是结构的样子.

--- UIView
   ---- ScrollView
       --- TableView
Run Code Online (Sandbox Code Playgroud)

.

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];
Run Code Online (Sandbox Code Playgroud)

在tableview中,我正在使用一个带有按钮的自定义tableview单元格.这是我的CellForRowAtIndex中按钮的代码

[cell.btnDelete addTarget:self action:@selector(deleteAppointment:) forControlEvents:UIControlEventTouchUpInside];
Run Code Online (Sandbox Code Playgroud)

现在要获取特定的行,我在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);
Run Code Online (Sandbox Code Playgroud)

但它仍然给出以下错误.

-[ExceptionCell indexPathForCell:]: unrecognized selector sent to instance 0x210a2fa0
Run Code Online (Sandbox Code Playgroud)

谁能帮我?

jun*_*dhu 6

它非常简单,在cellForRowAtIndexPath.只需标记您的按钮即可

cell.button.tag = indexPath.row;
Run Code Online (Sandbox Code Playgroud)

在按钮@selector方法中删除数组或字典(即您的dataSource)中的值

[array removeObjectAtIndex:button.tag];
Run Code Online (Sandbox Code Playgroud)

现在重新加载tableView.

[tableView reloadData];
Run Code Online (Sandbox Code Playgroud)