Ios Swift:从UITapgestureRecognitor获取任意信息

Ios Swift:从UITapgestureRecognitor获取任意信息,ios,swift,Ios,Swift,我有一个单元格中的图像列表,在UITableView中。出于我不想(过多)深入的原因,我无法使用didselectrowatinexpath来知道选择了哪一个,因为我使用的第三方模块添加了自己的父手势,并且我无法设置cancelsTouchesInView=false(这可以从技术上解决我的问题) 在这两种情况下,是否有一种方法可以将任意信息添加到视图中,以便当我作为发送者收到它时,我可以对其进行反思 如果这是HTML和JavaScript,你可以这样做 $(myImage).data('foo

我有一个单元格中的图像列表,在
UITableView
中。出于我不想(过多)深入的原因,我无法使用
didselectrowatinexpath
来知道选择了哪一个,因为我使用的第三方模块添加了自己的父手势,并且我无法设置
cancelsTouchesInView=false
(这可以从技术上解决我的问题)

在这两种情况下,是否有一种方法可以将任意信息添加到视图中,以便当我作为
发送者收到它时,我可以对其进行反思

如果这是HTML和JavaScript,你可以这样做

$(myImage).data('foo', 'bar')
$(anotherImage.data('foo', 'thunk')

$('img').on('click', function () {
  console.log($(this).data('foo')) // could be "foo" or "thunk"
})
迅速地

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  var cell = MyCustomTableViewCell()
  cell.userInteractionEnabled = true
  let tapped = UITapGestureRecognizer(target: self, action: Selector("myCallback:"))
  cell.addGestureRecognizer(tapped)


  // my imaginary world...
  cell.foo = self.extraData[indexPath.row]

  return cell
}

func myCallback(sender: AnyObject?) {
  println(sender.foo)
}

显然,上述方法不起作用,但有没有办法实现我的目标?

虽然我个人不建议使用太多,但如果您想在运行时将额外数据附加到对象,可以使用

关于如何在Swift中实现这一点,这里有一个很好的资源:


或者,UIView类有一个名为
tag
的属性,您可以将
indexPath.row
分配给该属性,以获取稍后点击的单元格:

cell.tag = indexPath.row
顺便说一句,你最好不要在细胞上工作。相反,当您要添加手势或其他子视图等时,请始终对其
contentView
属性进行操作

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    ...
    cell.contentView.userInteractionEnabled = true

    // Always remove previously added tap gestures because cells are reused
    // as you scroll up and down so you'll end up having multiple 
    // recognizers on the same cell otherwise.
    for recognizer in cell.contentView.gestureRecognizers {
        cell.contentView.removeGestureRecognizer(recognizer)
    }

    cell.contentView.addGestureRecognizer(
        UITapGestureRecognizer(target: self, action: "myCallback:"))

    cell.contentView.tag = indexPath.row

    ...
    return cell
}
在回调函数中获取单元格非常简单:

(假定只有一个节,因此indexath.section=0)


杰出的这很有魅力。还有,有什么理由不在单元格上设置可识别的手势?在我的示例中,它工作得很好(意思是,我得到了回调)。我认为即使您在cell上也设置了识别器,它仍然可以工作。但是,根据Sorry,最好始终使用
contentView
而不是单元格本身。我还不知道我能做到。我很确定用户是
func myCallback(sender: UIGestureRecognizer) {
    let indexPath = NSIndexPath(forRow: sender.view.tag , inSection: 0)         

    if let cell = tableView.cellForRowAtIndexPath(indexPath) {
        print("Cell \(cell) has been tapped.")
    }
}