【发布时间】:2015-09-02 17:46:08
【问题描述】:
我在 TableViewController 中的不同 UIView 上创建和识别了几个点击手势,并且可以正确识别不同的手势。如这段代码所示:
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
}
我的手柄水龙头如下所示:
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 的水龙头。无论我点击单元格的哪个位置,它都只会调用 view2 点击。我尝试过使用不同的 Selector 函数(例如,handleTapOne:用于 View1,handleTapTwo:用于 View2),但我似乎无法弄清楚如何做到这一点。
它再次在我的 UITableViewController 中工作,但是当我尝试将所有点击识别器移动到 UITableViewCell 时它不起作用。
感谢您的帮助。
【问题讨论】:
-
您在
override func awakeFromNib()中的代码看起来不对,应该是self.View1.addGestureRecognizer(tapOnView1)吗? -
好吧,我有点傻。谢谢。那确实解决了我的问题。我快疯了,像这样愚蠢的事情让我无法忍受。感谢您的回答。
标签: ios swift uitableview uitapgesturerecognizer