animate a change in images in an uiimageview to look like a book page flip in swift

You can use Core Animation along with UIView.animate() method to achieve page flip animation on UIImageview. The core animation provides a 3D effect to animation for the UIView class. In the animation, we will swap two images using UIView.transition() method. Here is the sample code that shows how to animate a page flip.

main.swift
func flip(from fromView: UIImageView, to toView: UIImageView, duration: TimeInterval, completion: ((Bool) -> Void)? = nil) {
    guard let fromImage = fromView.image,
          let toImage = toView.image else { return }
    
    let containerView = UIView(frame: CGRect(origin: .zero, size: fromView.frame.size))
    containerView.clipsToBounds = true
    let transitionOptions = UIView.AnimationOptions.transitionFlipFromRight
    
    let fromImageView = UIImageView(image: fromImage)
    let toImageView = UIImageView(image: toImage)
    
    fromImageView.frame = containerView.bounds
    toImageView.frame = containerView.bounds
    
    containerView.addSubview(toImageView)
    
    UIView.transition(from: fromView,
                      to: containerView,
                      duration: duration,
                      options: transitionOptions) { (success) in
                        fromView.image = toImage
                        completion?(success)
    }
}
974 chars
25 lines

You can call this method by passing the two UIImageViews and the desired duration of animation. Here is an example of how to call this method:

main.swift
let imageView1 = UIImageView(frame: CGRect(x: 0, y: 0, width: 300, height: 400))
let imageView2 = UIImageView(frame: CGRect(x: 0, y: 0, width: 300, height: 400))

//Assign images to image views
imageView1.image = UIImage(named: "image1.png")
imageView2.image = UIImage(named: "image2.png")

//Call the flip function
flip(from: imageView1, to: imageView2, duration: 1.0) { (success) in
    //Flip animation completed
}
418 chars
12 lines

I hope this helps you to create amazing page flip animations in your iOS applications.

gistlibby LogSnag