UITableViewCell中的多个Tap手势

时间:2015-09-02 17:46:08

标签: ios swift uitableview uitapgesturerecognizer

我在TableViewController中的不同UIViews上创建并识别了几个轻击手势,并且正确识别了不同的手势。如下面的代码所示:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! CustomCell
  let tapOnView1 = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
  let tapOnView2 = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
  cell.View1.addGestureRecognizer(tapOnView1)
  cell.View1.userInteractionEnabled = true
  cell.View2.addGestureRecognizer(tapOnView1)
  cell.View2.userInteractionEnabled = true
  return cell
}

My Handle tap看起来像这样:

func handleTap(sender:UITapGestureRecognizer) {
        let tappedView = sender.view
        self.tableView.beginUpdates()

        if tappedView == cell.View1 {
            print("View 1 Tapped")
        } else if tappedView == cell.View2 {
            print("View 2 Tapped")
        }
}

我想将所有这些代码移动到我的CustomCell UITableViewCell类,因为实际上有几个UIViews需要在点击时采取不同的操作。另外,将它们全部移动到Cell本身似乎是正确的做法。我搜索了答案,但我看到的唯一真正的答案是使用按钮,有几个原因,如果没有一些严重的重构和重写,这对我来说真的不是一个选择。我已经在CustomCell类中对以下代码尝试了几次迭代:

override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        let tapOnView1 = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
        addGestureRecognizer(tapOnView1)

        let tapOnView2 = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
        addGestureRecognizer(tapOnView2)

    }

和这个handleTap函数:

func handleTap(sender: UITapGestureRecognizer) {
        if delegate != nil && item != nil {
            if sender.view == view1 {
                print("view1 tapped")
            } else {
                print("view2 tapped")
            }
        }

    }

永远不会调用view1的tap。它只会调用view2 tap,无论我在哪个单元格中点击。我尝试使用不同的Selector函数(即handleTapOne:用于View1,handleTapTwo:用于View2),但我似乎无法弄清楚如何执行此操作。

同样它在我的UITableViewController中工作,但是当我尝试将所有点击识别器移动到UITableViewCell时,它不起作用。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

iphonic在上面回答了我的问题。我猜我是个白痴。长时间盯着一个问题并错过最简单的事情。

相关问题