简体   繁体   English

UITapGestureRecognizer 不适用于 UIView 动画

[英]UITapGestureRecognizer does not work with UIView animate

I'm trying to call an action when I tap on a UIImage at the time of its animation.当我在动画播放时点击 UIImage 时,我试图调用一个动作。 I've seen similar questions, but I could not apply these solutions to my case.我见过类似的问题,但我无法将这些解决方案应用于我的案例。 Please help.请帮忙。

xcode 9.2 swift 4 Xcode 9.2 快速 4

import UIKit

class MyCalssViewController: UIViewController {

    @IBOutlet weak var myImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // action by tap
        let gestureSwift2AndHigher = UITapGestureRecognizer(target: self, action:  #selector (self.actionUITapGestureRecognizer))
        myImageView.addGestureRecognizer(gestureSwift2AndHigher)

    }

    // action by tap
    @objc func actionUITapGestureRecognizer (){

        print("actionUITapGestureRecognizer - works!") // !!! THIS DOES NOT WORK !!!

    }

    // hide UIImage before appear
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        myImageView.center.y += view.bounds.height

    }

    // show UIImage after appear with animation
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        UIView.animate(withDuration: 10, animations: {
            self.myImageView.center.y -= self.view.bounds.height
        })
    }
}

You just missed a line, enabling user interaction on the view.您只是错过了一行,从而启用了视图上的用户交互。

override func viewDidLoad() {
    super.viewDidLoad()

    // action by tap
    let gestureSwift2AndHigher = UITapGestureRecognizer(target: self, action:  #selector (self.actionUITapGestureRecognizer))
    myImageView.isUserInteractionEnabled = true
    myImageView.addGestureRecognizer(gestureSwift2AndHigher)

}
  let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.clickedImageView(_:)))
  myImageview.isUserInteractionEnabled = true
  myImageview.addGestureRecognizer(tapGesture)

// MARK: - Gesture Recognizer action

    func clickedImageView(_ sender: UITapGestureRecognizer) {
       // Write your action here.
    }

You need to pass in the option .allowUserInteraction like this:您需要像这样传入选项.allowUserInteraction

UIView.animate(withDuration: 10, delay: 0, options: .allowUserInteraction, animations: {
    ...
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM