2015-05-25 13 views
0

我正在开发一个待办事宜应用程序。在我的应用程序中,我按下复选框按钮来删除一行。我为了给indexPath.row传递到我的复选框按钮编写代码:我如何将indexPath(而不是indexPath.row)传递给我的IBAction,用于我的UITableViewCell

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)?

回答

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() 
} 
+0

谢谢,这工作! – nintyapple

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) 
+0

这很危险。不同版本的iOS可以在按钮和单元格之间具有不同数量的视图。 – rdelmar

0

如果只有一个部分表视图比我建议你变量分配给UIButton的实例和标记值应该等于indexPath.row

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

相关问题