简体   繁体   中英

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. I've seen similar questions, but I could not apply these solutions to my case. Please help.

xcode 9.2 swift 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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