Search code examples
swiftuitapgesturerecognizer

How to add transition on UITapGestureRecognizer in Swift 3?


I'm trying to make the image view full screen when I click on the small image. But the image show very fast when I clicked on the image. Can I add some transition time to delay the full screen image showing?

@IBAction func uploadImgAction(_ sender: Any) {
    let tapgesture = UITapGestureRecognizer(target: self, action: #selector(DeleteJobViewController.tap))
    tapgesture.numberOfTapsRequired = 1
    reasonImg.addGestureRecognizer(tapgesture)
}

func tap(){
    print("tap")
    let newImageView = UIImageView(image: reasonImg.image)
    newImageView.frame = self.view.frame
    newImageView.backgroundColor = .black
    newImageView.contentMode = .scaleAspectFit
    newImageView.isUserInteractionEnabled = true
    let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage))
    newImageView.addGestureRecognizer(tap)
    self.view.addSubview(newImageView)
}

func dismissFullscreenImage(sender: UITapGestureRecognizer) {
    sender.view?.alpha = 1
    UIView.animate(withDuration: 1.5, animations: {
        sender.view?.alpha = 0
        sender.view?.removeFromSuperview()
    })
}

Solution

  • Try replacing the self.view.addSubview(newImageView) line with:

    DispatchQueue.main.async {   
      UIView.transition(with: self.view, duration:0.6, options: UIViewAnimationOptions.showHideTransitionViews, animations: {
        self.view.addSubview(self.newImageView)
      }, completion: nil)
    }
    

    You can also try setting newImageView.alpha = 0 before running this code:

    UIView.animate(withDuration: 1.5, animations: {
      self.newImageView.alpha = 1.0
    })
    

    For animating the disappear effect, in the code above, replace the addSubview statement with newImageView.removeFromSuperview(). And similarly you can set this after you have set the newImageView.alpha = 1:

    func dismissFullscreenImage(sender: UITapGestureRecognizer) {
        UIView.animate(withDuration: 1.5, animations: {
              self.newImageView.alpha = 0
        })
    }
    

    EDIT:

    Please add newImageView as a property at the top of your view controller.

    Then in your tap function set this instead of let newImageView:

    self.newImageView = UIImageView(image: reasonImg.image)
    

    Now if you run the code it should compile.