iOS - Card flip animation
Your problem is that your UIImageViews are directly on the "full page" view.
transitionFromView removes the fromView from its superview and adds the toView on the superview with the given animation. Thus, it animates the superview.
You should include a UIView that servers as a container and have both imageViews as subviews. Add your tap gesture on the containerview. Also, you should not have weak references to the imageViews, since once you have done the animation once, your reference to the back imageView will be gone. It is probably better to add these in code rather than storyboard. No need to hide the imageViews.
Here are some sample code:
class MyViewController: UIViewController {
@IBOutlet weak var containerView: UIView!
private let backImageView: UIImageView! = UIImageView(image: UIImage(named: "back"))
private let frontImageView: UIImageView! = UIImageView(image: UIImage(named: "front"))
private var showingBack = false
override func viewDidLoad() {
super.viewDidLoad()
frontImageView.contentMode = .ScaleAspectFit
backImageView.contentMode = .ScaleAspectFit
containerView.addSubview(frontImageView)
frontImageView.translatesAutoresizingMaskIntoConstraints = false
frontImageView.spanSuperview()
let singleTap = UITapGestureRecognizer(target: self, action: #selector(flip))
singleTap.numberOfTapsRequired = 1
containerView.addGestureRecognizer(singleTap)
}
func flip() {
let toView = showingBack ? frontImageView : backImageView
let fromView = showingBack ? backImageView : frontImageView
UIView.transitionFromView(fromView, toView: toView, duration: 1, options: .TransitionFlipFromRight, completion: nil)
toView.translatesAutoresizingMaskIntoConstraints = false
toView.spanSuperview()
showingBack = !showingBack
}
}
If you have a button
that holds "card" as a variable, and you want to change his image to a new image called "1". All you have to do is this:
let image = UIImage(named: "1")
card.setImage(image, for: .normal)
UIView.transition(with: card, duration: 2, options: .transitionFlipFromRight, animations: nil, completion: nil)