点击Cell Accessory

时间:2016-01-21 14:52:13

标签: ios swift uitableview accessoryview

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

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
     //Segue to another view
}

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

当单元格没有完成时,我想要一个可以点击的空检查(我知道我可以添加自定义图像附件),点击允许用户跳过segue并快速将单元格标记为完了。但我似乎无法兼顾:

  1. 点击单元格的主体应该调用didSelectRowAtIndexPath
  2. 点击附件视图(空复选标记)应调用另一组代码。
  3. 我已经尝试过accessoryButtonTappedForRowWithIndexPath但它似乎甚至没有被调用。

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

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

3 个答案:

答案 0 :(得分:1)

它是Objective-C解决方案。 当您添加自己的accessoryButton时,不会调用'accessoryButtonTappedForRowWithIndexPath'的tableviewDelegate方法。 您应该做的是,为该方法创建UIButtonaddTarget,然后在accessoryButton上将其添加为tableViewCell。同时将tag值设置为按钮index path.row,以便您知道点击了哪一行。

答案 1 :(得分:1)

您应该将UIButton添加到自定义UITableViewCell。然后,您可以通过说cell.button.addTarget(self, action: "finishedPress:", forControlEvents: .TouchUpInside)之类的内容为名为pressedFinished的按钮添加目标  或者什么然后在pressFinished你可以说如下:

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
}

使用标签通常不是一个好习惯,因为它们没有固有的含义。映射到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]
}

答案 2 :(得分:0)

我选择了我认为给出了彻底答案的答案,这帮助了我。但是,我偏离了这个答案,并希望分享这个:

使附件视图显示/消失

我将多个列表加载到同一个storyboard表中。有时列表应显示指示符,有时则不需要附件。为此,我在故事板中添加了一个按钮,垂直居中,尾随= 0到右侧容器视图。然后我给它宽度为0,并在我的代码中给了该约束一个IBOutlet。当我想要配件时,我只是给它一个宽度。为了使它消失,我将其宽度设置回0。

附件和核心数据

配件有点痛苦,因为如果用户检查某些东西然后关闭应用程序,他们希望它会被记住。因此,对于每个更改,您需要在CoreData中保存该单元格状态。我添加了一个名为" state"并给它一个"选择的值#34;当配件出现填充时。

这也意味着我必须在检索列表时按该属性排序。如果您已经有了排序描述符,那么现在需要几个。

相关问题