UITableView自定义删除按钮功能



作为默认行为,一旦您要删除表格视图的任何单个单元格,您将点击CEL左侧的删除按钮,删除确认按钮将显示在单元格右侧,然后继续点击此按钮,此行将被删除。对于此行为,您需要有 2 个步骤才能删除行。有什么方法只能点击删除按钮(在单元格左侧(删除单元格而不点击确认按钮?

您的意思是仅通过向左交换删除该行吗?忽略删除按钮?

您可以使用UISwipeGestureRecognizer,如下所示:

class YourViewController: UITableViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        var swipe = UISwipeGestureRecognizer(target: self, action: #selector(self.didSwipe))
        self.tableView.addGestureRecognizer(swipe)
    }
    func didSwipe(recognizer: UIGestureRecognizer) {
        if swipe.state == UIGestureRecognizerState.Ended {
            let swipeLocation = swipe.locationInView(self.tableView)
            if let swipedIndexPath = tableView.indexPathForRowAtPoint(swipeLocation) {
                if let swipedCell = self.tableView.cellForRowAtIndexPath(swipedIndexPath) {
                    self.cellObjectsArray.remove(at: swipedIndexPath.row)
                    tableView.deleteRows(at: [swipedIndexPath], with: .fade)
                }
            }
        }
    }
}

可以通过实现以下委托方法来删除单元格,但这是一个两步过程,

  1. 滑动单元格以找到右侧的删除确认按钮
  2. 单击删除(将调用commitEditingStyle(

如果您想通过一个步骤/单击来做到这一点,请在UITableViewCell中添加一个自定义按钮,并在其选择器中获取UITableViewCellindexpath并从数据源中删除对象并重新加载表,这类似于commitEditingStyle方法中实现的代码。


- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"Delete";
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Delete the object at `indexPath` from datasource
    //Update UI, by reloading section/entire table
}

最新更新