如何将 indexPath(不是 indexPath.row)传递到我的 UITableViewCell 的 IBAction

How do I pass indexPath (not indexPath.row) into my IBAction for my UITableViewCell

我正在开发待办事项应用程序。在我的应用程序中,我按下复选框按钮来删除一行。我写这段代码是为了将 indexPath.row 传递到我的复选框按钮中:

cell.checkbox.tag = indexPath.row
cell.checkbox.addTarget(self, action: "checkAction:", forControlEvents: .TouchUpInside)

第一个代码允许我访问 indexPath.row,第二个代码允许我在按下按钮时创建一个函数。这是我在按下按钮时使用的功能:

@IBAction func checkAction(sender: UIButton) {
    taskMgr.removeTask(sender.tag)
    tblTasks.reloadData()
}

现在,我想在删除时添加动画,这样看起来就不会那么突然了。我将使用的代码是这样的:

tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)

但是,我只能在我的 checkAction 函数中访问 indexPath.row。如何访问 indexPath(不牺牲 indexPath.row)?

如果您在重新加载整个 table 之前四处移动行或者添加或删除行,标签可能会给您带来错误的行。因此,您可以在按钮方法中使用 indexPathForRowAtPoint: 而不是使用标签来获取 indexPath.

@IBAction func checkAction(sender: UIButton) {

    let point = sender.convertPoint(CGPointZero, toView: self.tableView)
    let indexPath = self.tableView.indexPathForRowAtPoint(point)
    taskMgr.removeTask(indexPath.row)
    tblTasks.reloadData()
}

您可以在视图控制器中保存索引路径:

class ViewController: UITableViewController {

    var toDeletedIndexPath: NSIndexPath?

    @IBAction func checkAction(sender: UIButton) {
        var cell = sender
        do {
            cell = cell.superview
        } while cell.isKindOfClass(UITableViewCell)

        self.toDeletedIndexPath = self.tableView.indexPathForCell(cell)

        tblTasks.reloadData()
    }
}

然后

tableView.deleteRowsAtIndexPaths([self.toDeletedIndexPath], withRowAnimation: UITableViewRowAnimation.Automatic)

如果您在 table 视图中只有一个部分,那么我建议您将标签分配给 UIButton 的实例,标签值应等于 indexPath.row

但是如果你有多个部分并且你需要访问 index path 而不是通过发件人的按钮的触摸事件我认为你应该继承 UIButton 并添加 NSIndexPath 属性。当您创建 Custom UIButton 的实例时,然后将索引路径分配给 custom button instanceindex path 属性。现在,当单击该按钮时,您可以访问索引路径,因为它是 Custom UIButton.

的属性