在表视图单元格中使用按钮使单元格出列

时间:2016-03-31 22:49:56

标签: swift uitableview

基本上,我有一个自定义表格视图单元格,列出了潜在的员工。此单元格包含一些标签和一个按钮。我想要的是按钮移除单元格,但我能找到的就是:

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
  numbers.removeAtIndex(indexPath.row)    
  tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}

}

只允许您在滑动时删除单元格,然后选择“删除”

我想我应该在tableViewController.swift文件中创建一个函数来删除给定行的单元格,并在我的自定义单元格类中创建一个将调用所述函数的IBAction。

删除给定行的单元格的功能是什么样的?但在这种情况下,单元格是否也知道它所在的行或者是tableViewController的作业?

3 个答案:

答案 0 :(得分:1)

  1. cellForRowAtIndexPath设置cell.button.tag = indexPath.row

  2. 向按钮添加目标:cell.button addTarget:...

  3. 在按钮方法中,删除dataArray索引为button.tag的项目。然后刷新tableView self.tableView reloadData

答案 1 :(得分:1)

您可以使用UIButton的tag属性来存储要删除的单元格的索引,并在处理程序中使用该标记属性来定位正确的单元格。在我的示例代码中,我只是做了一个假设 你只有一个部分就是为什么它被设置为零。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
  ...
  ...
  cell.button.tag = indexPath.row
  let tapGesture = UITapGestureRecognizer(target: self, action: Selector("handleDeleteTap:"))
  cell.button.addGestureRecognizer(tapGesture)

}

func handleDeleteTap(sender: UITapGestureRecognizer)
{
  if let button = sender.view as? UIButton
  {
    let indexPath = NSIndexPath(forRow: button.tag, inSection: 0)
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) 
  }
}

答案 2 :(得分:1)

1)您必须在cellForRowAtIndexPath中为您的按钮定义一个操作:

...
myButton.addTarget(self, action: "buttonTappedDelete:", forControlEvents: .TouchUpInside)
...

2)你必须实现选择器:
2.1)获取按钮所在的单元格 2.2)获取单元格的索引路径 2.3)从表格视图中删除单元格并更新数据。

func buttonTappedDelete(sender: UIButton) {
    let cell = sender.superview!.superview as! UITableViewCell
    let indexPath = self.tableView.indexPathForCell(cell)!
    self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    // update your data model, call `self.tableView.reloadData()`
}