问题
I have a view with the tap function (user interaction is enabled). If I set it without changing alpha it works well. But if I try to change alpha of this view with delay, it cannot be tapped during this animation. Could somebody help?
Here is my code:
import UIKit
class ViewController: UIViewController {
var myView = UIView()
var n = 0
override func viewDidLoad() {
super.viewDidLoad()
setView()
changeAlpha()
}
func changeAlpha() {
UIView.animate(withDuration: 5) {
self.myView.alpha = 0.1
}
}
func setView() {
let size = view.frame.width
myView = UIView(frame: CGRect(x: 0, y: 0, width: size/3, height: size/3))
myView.center = view.center
myView.backgroundColor = UIColor.red
view.addSubview(myView)
myView.isUserInteractionEnabled = true
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(gameObjectTapped(_:)))
myView.addGestureRecognizer(tapGestureRecognizer)
}
@objc func gameObjectTapped(_ recognizer:UITapGestureRecognizer) {
print("# tap \(n)")
n+=1
}
回答1:
Run the animation with option .allowUserInteraction
:
UIView.animate(withDuration: 5, delay: 0, options: [.allowUserInteraction], animations: {
self.myView.alpha = 0.1
}, completion: nil)
回答2:
change your
UIView.animate(withDuration: 5) {
self.myView.alpha = 0.1
}
to
UIView.animate(withDuration: 5, delay: 0.0, options: .allowUserInteraction, animations: {
self.myView.alpha = 0.1
}, completion: nil)
来源:https://stackoverflow.com/questions/48559553/enable-user-interaction-by-changing-alpha-swift-ios