0

可能重复:
通过单击按钮替换滑动操作以删除

我有以下代码。

- (void) tableView: (UITableView *) tableView commitEditingStyle: (UITableViewCellEditingStyle) editingStyle forRowAtIndexPath: (NSIndexPath *) indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [appointments removeObjectAtIndex: indexPath.row];  // manipulate your data structure.
        [tableView deleteRowsAtIndexPaths: [NSArray arrayWithObject: indexPath]
                         withRowAnimation: UITableViewRowAnimationFade];
       NSLog(@"row deleted");  // Do whatever other UI updating you need to do.
    }
} 

当我在单元格上滑动时,将执行这段代码。但我想要的是当我在自定义表格视图单元格中按下按钮时执行此代码。就像您在下面的屏幕截图中看到的那样,我的 tableview 上有 2 个按钮。

在此处输入图像描述

当用户按下“X”按钮时,删除按钮应该像滑动单元格时一样展开。我的单元格附加了以下操作。

-(IBAction) deleteAppointment:(id) sender{
   //show swipe delete button
}

并通过以下方式将其附加到我的 cellForRowAtIndex 中。

cell.deleteAppointment.tag = indexPath.row;
[cell.deleteAppointment addTarget:self action:@selector(deleteAppointment:) forControlEvents:UIControlEventTouchUpInside];
4

1 回答 1

0

只需在您的单元格中添加带有按钮的目标并将标签设置为每个按钮,如下所示..

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    /////your code
    UIButton *btnClose = [[UIButton alloc]initWithFrame:CGRectMake(270, 7, 20, 20)];
    btnClose.tag = indexPath.row;
    [btnClose setImage:[UIImage imageNamed:@"closeImage.png"] forState:UIControlStateNormal];
    [btnClose addTarget:self action:@selector(deleteAppointment:) forControlEvents:UIControlStateNormal];
    [cell addSubview:btnClose];
    return cell;
}

在方法中看到这样......

    - (IBAction)deleteAppointment:(id)sender {

            // here bellow code for swipe the close button in cell
            UIButton *btn = (UIButton *)sender;
            int SelectedRowNo = btn.tag;
            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:0.3];
            [btn setFrame:CGRectMake(btn.frame.origin.x - 50, btn.frame.origin.y, btn.frame.size.width, btn.frame.size.height)];
            [UIView commitAnimations];

            //// here bellow code for delete raw from table
            /*
             [appointments removeObjectAtIndex: SelectedRowNo];
             UITableViewCell *clickedCell = (UITableViewCell *)[[sender superview] superview];
             NSIndexPath *clickedButtonPath = [yourTableView indexPathForCell:clickedCell];
             [yourTableView deleteRowsAtIndexPaths: [NSArray arrayWithObject: clickedButtonPath]
             withRowAnimation: UITableViewRowAnimationFade];
             NSLog(@"row deleted");  // Do whatever other UI updating you need to do.
             */
}

我希望这对你有帮助..

于 2012-11-30T10:25:23.130 回答