ios - 如何监听同一 View 中不同控件上的点击手势?

标签 ios swift uitapgesturerecognizer

我有一个控件的两个副本(称为 RatingControl)。如何编写处理程序,当有人双击它们时,可以在正确的对象上调用这些处理程序?

我有:

@IBOutlet weak var ratingControl: RatingControl!
@IBOutlet weak var ratingControl2: RatingControl!

TableViewController内,然后

override func viewDidLoad() {
    super.viewDidLoad()

    let tapGR = UITapGestureRecognizer(target: ratingControl, action: #selector(RatingControl.doubleTap(_:)))
    tapGR.numberOfTapsRequired = 2
    self.view.addGestureRecognizer(tapGR)

    let tapGR2 = UITapGestureRecognizer(target: ratingControl2, action: #selector(RatingControl.doubleTap(_:)))
    tapGR2.numberOfTapsRequired = 2
    self.view.addGestureRecognizer(tapGR2)

}

RatingControl.doubleTap(_) 是一个无害的事件处理程序。

当双击第二个评级控件时,将调用 doubleTap 方法,但会在第一个评级控制对象上分派(dispatch)!

我尝试在一个 UITapGestureRecognizer 上设置两个目标,但遇到了同样的问题。

非常感谢!

最佳答案

您需要将手势识别器添加到两个评级控件,而不是 self.view

试试这个:

let tapGR = UITapGestureRecognizer(target: self, action: #selector(RatingControl.doubleTap(_:)))
tapGR.numberOfTapsRequired = 2
ratingControl.addGestureRecognizer(tapGR) // ratingControl, not self.view
let tapGR2 = UITapGestureRecognizer(target: self, action: #selector(RatingControl.doubleTap(_:))) 
tapGR2.numberOfTapsRequired = 2
ratingControl2.addGestureRecognizer(tapGR2) // ratingControl2, not self.view

关于ios - 如何监听同一 View 中不同控件上的点击手势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41928196/

相关文章:

ios - 在 Swift iOS 中的 Google map 上选择时动画 map 标记

ios - 如何在 Swift 中解析由蓝牙设备发送的 float ?

iphone - 为什么 Xcode 无法识别 -ignoreTouch :forEvent: in UITapGestureRecognizer subclass?

ios - 圆形 View 上的手势识别器

ios - 什么时候在 iOS AutoLayout 中使用 Multiplier?

ios - UITextField 上的 UITapGestureRecognizer 在 IOS 7.1 中不再有效

objective-c - 无法将字符串正确转换为日期 objective-c

iphone - 如何使用 UIBezierPath 裁剪图像?

ios - 在 UICollectionViewReusableView header 中访问 UIViews 的委托(delegate)方法

ios - 在 Xcode 中使用带有可重用单元格的按钮和 TextFields