对于Swift 3项目,我在UIImageView项目上使用自定义路径动画。守则大纲如下:
// parentView and other parameters are configured externally
let imageView = UIImageView(image: image)
imageView.isUserInteractionEnabled = true
let gr = UITapGestureRecognizer(target: self, action: #selector(onTap(gesture:)))
parentView.addGestureRecognizer(gr)
parentView.addSubview(imageView)
// Then I set up animation, including:
let animation = CAKeyframeAnimation(keyPath: "position")
// .... eventually ....
imageView.layer.add(animation, forKey: nil)onTap方法是以标准方式声明的:
func onTap(gesture:UITapGestureRecognizer) {
print("ImageView frame is \(self.imageView.layer.visibleRect)")
print("Gesture occurred at \(gesture.location(in: FloatingImageHandler.parentView))")
}问题是,每次我调用addGestureRecognizer时,前面的手势识别器都会被覆盖,因此任何检测到的抽头都会指向最后添加的图像,并且位置无法准确检测(因此,如果有人在parentView上的任何地方点击,它仍然会触发onTap方法)。
如何在每次图像查看的基础上准确地检测出一个抽头?由于自定义路径动画需求,我不能使用UIView.animate或其他方法,而且我也不能创建覆盖透明的UIView来覆盖父视图,因为我需要这些“浮动器”来不吞咽这些事件。
发布于 2017-04-28 15:42:37
由于图层不更新它们的帧/位置等,我需要在我编写的图像视图子类(FloatingImageView)中添加以下内容:
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let pres = self.layer.presentation()!
let suppt = self.convert(point, to: self.superview!)
let prespt = self.superview!.layer.convert(suppt, to: pres)
return super.hitTest(prespt, with: event)
}我还将手势识别器移动到父视图,因此在任何时候只有一个GR,并为每个被添加的子视图创建了一个唯一的标记。处理程序如下所示:
func onTap(gesture:UITapGestureRecognizer) {
let p = gesture.location(in: gesture.view)
let v = gesture.view?.hitTest(p, with: nil)
if let v = v as? FloatingImageView {
print("The tapped view was \(v.tag)")
}
}其中FloatingImageView是UIImageView子类。
这种方法在iOS 10的一本书(以及WWDC)中进行了描述,并且也适用于iOS 9。我仍然在评估基于UIViewPropertyAnimator的tap检测,所以如果您能给我一个如何使用UIViewPropertyAnimator来完成上述操作的示例,我将把您的答案标记为正确的答案。
发布于 2017-04-27 08:38:39
目前还不清楚您想要实现什么,但我认为您应该在imageView中添加手势识别器,而不是向parentView中添加手势识别器。
所以这个:
parentView.addGestureRecognizer(gr)应由以下内容取代:
imageView.addGestureRecognizer(gr)在您的onTap函数中,您可能应该这样做:
print("ImageView frame is \(gesture.view.layer.visibleRect)")
print("Gesture occurred at \(gesture.location(in: gesture.view))")发布于 2017-04-28 09:17:16
我认为您可以检查属于imageView或不属于onTap函数的抽头位置。如下所示:
func ontap(gesture:UITapGestureRecognizer) {
let point = gesture.location(in: parentView)
if imageView.layer.frame.contains(point) {
print("ImageView frame is \(self.imageView.layer.visibleRect)")
print("Gesture occurred at \(point)")
}
}https://stackoverflow.com/questions/43651351
复制相似问题