点击手机配件

Dav*_*e G 5 uitableview accessoryview ios swift

我有一个带有自定义单元格的 UITableView。通常当用户点击单元格时,会触发此功能:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
     //Segue to another view
}
Run Code Online (Sandbox Code Playgroud)

如果在该视图中他们将单元标记为已完成,则当他们返回代码时将添加标准检查附件。

当单元格未完成时,我想要一个可以点击的空支票(我知道我可以添加自定义图像附件),点击允许用户跳过转场并快速将单元格标记为已完成。但我似乎无法让两者都工作:

  1. 点击单元格的主体应该调用 didSelectRowAtIndexPath
  2. 点击附件视图(空复选标记)应该调用一组不同的代码。

我已经尝试过accessoryButtonTappedForRowWithIndexPath,但它似乎没有被调用。

func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) { 
     //Shortcut code to change the cell to "finished"
}
Run Code Online (Sandbox Code Playgroud)

是否可以单击主体触发一组代码,单击附件视图触发另一组代码?如果是这样,怎么办?

bey*_*ulf 1

您应该将 UIButton 添加到自定义 UITableViewCell 中。然后,您可以为该按钮添加一个名为pressedFinished 的目标,通过说类似的cell.button.addTarget(self, action: "finishedPress:", forControlEvents: .TouchUpInside) 话,然后在pressedFinished 中您可以说类似以下的话:

func pressedFinished(sender:UIButton)
{
   let location = self.tableView.convertPoint(sender.bounds.origin, fromView: sender)
   let indexPath = self.tableView.indexPathForRowAtPoint(location)
   //update your model to reflect task at indexPath is finished and reloadData
}
Run Code Online (Sandbox Code Playgroud)

使用标签通常不是一个好习惯,因为它们没有固有的含义。此外,映射到 indexPath.row 的标签仅在表有一个部分时才起作用。

另一种选择可能是使用 UITableViewRowAction:

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath:      NSIndexPath) -> [AnyObject]? {
  let rowAction : UITableViewRowAction
  if model[indexPath].finished
  {
      rowAction = UITableViewRowAction(style: .Normal, title: "Mark as Unfinished", handler: {(rowAction:UITableViewRowAction,indexPath:NSIndexPath)->() in
      //mark as unfinished in model and reload cell
      })
 }else{
      rowAction = UITableViewRowAction(style: .Normal, title: "Mark as Finished", handler: {(rowAction:UITableViewRowAction,indexPath:NSIndexPath)->() in
      //mark as finished in model and reload cell
      })
  }
  return [rowAction]
}
Run Code Online (Sandbox Code Playgroud)