我正在开发一个待办事项。在我的应用程序中,我按一个复选框按钮删除一行。我编写此代码是为了将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)?
答案 0 :(得分:4)
如果您移动行或添加或删除行,标记可能会给您一个错误的行,直到您重新加载整个表。因此,您可以在按钮方法中使用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()
}
答案 1 :(得分:0)
您可以在视图控制器中保存indexPath:
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)
答案 2 :(得分:0)
如果您在表格视图中只有一个部分,我建议您将标记分配给UIButton
的实例,并且标记值应该等于indexPath.row
但是如果您有多个部分而且需要访问index path
而不是通过发件人触摸按钮事件,那么我认为您应该继承UIButton
并添加NSIndexPath
属性。当您创建Custom UIButton
的实例时,请为index path
的{{1}}属性分配索引路径。现在,当单击该按钮时,您可以访问索引路径,因为它是custom button instance
的属性。