我尝试检测 UIImageView 在动画过程中的点击,但它不起作用。
我做什么(swift 4):
通过 StoryBoard 添加 UIImageView:
@IBOutlet weak var myImageView: UIImageView!
做动画:
override func viewWillAppear (_ animated: Bool) {
super.viewWillAppear (animated)
myImageView.center.y + = view.bounds.height
}
override func viewDidAppear (_ animated: Bool) {
super.viewDidAppear (animated)
UIView.animate (withDuration: 10, delay: 0, options: [.repeat, .autoreverse, .allowUserInteraction], animations: {
self.myImageView.center.y - = self.view.bounds.height
})
}
尝试检测点击:
override func viewDidLoad () {
super.viewDidLoad ()
let gestureSwift2AndHigher = UITapGestureRecognizer (target: self, action: #selector (self.actionUITapGestureRecognizer))
myImageView.isUserInteractionEnabled = true
myImageView.addGestureRecognizer (gestureSwift2AndHigher)
}
@objc func actionUITapGestureRecognizer () {
print ("actionUITapGestureRecognizer - works!")
}
请在对问题进行投票之前,确保没有针对此类问题的正常公式化答案,初学者可以理解并且在版本 2 以上的 swift 中编写,因此我不能将它们应用于我的案例。
研究这个问题,我意识到有必要调整框架!?但这对我来说仍然很难。请告诉我我需要在下面的代码中添加或更改什么。
感谢您的帮助。
class ExampleViewController: UIViewController {
@IBOutlet weak var myImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// action by tap
let gestureSwift2AndHigher = UITapGestureRecognizer(target: self, action: #selector (self.actionUITapGestureRecognizer))
myImageView.isUserInteractionEnabled = true
myImageView.addGestureRecognizer(gestureSwift2AndHigher)
}
// action by tap
@objc func actionUITapGestureRecognizer (){
print("actionUITapGestureRecognizer - works!") // !!! IT IS DOES NOT WORK !!!
}
// hide UIImageView before appear
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
myImageView.center.y += view.bounds.height
}
// show UIImageView after appear with animation
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.animate(withDuration: 10, delay: 0, options: [.repeat, .autoreverse, .allowUserInteraction], animations: {
self.myImageView.center.y -= self.view.bounds.height
})
}
}
最佳答案
要检测移动(动画) View 上的触摸,只需使用表示层覆盖 hitTest
:
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
return (layer.presentation()!.frame)
.contains(self.convert(point, to: superview!)) ? self : nil
}
举个例子
它适用于所有手势识别器
请勿在 View Controller 级别修改任何框架或任何其他内容
简单地继承 View 本身,添加上面的覆盖
当然不要忘记这一点,如果您想在项目被抓取后停止动画,请(在您的 View Controller 中)使用 yourPropertyAnimator?.stopAnimation(true) , yourPropertyAnimator = nil
关于ios - 如何在动画过程中检测 UIImageView 上的点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48034328/