Overview
In this post, I’ll show you how to transition between 2 UIViews on tap in swift.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// ### in viewDidLoad ###
let container = UIView()
let redSquare = UIView()
let blueSquare = UIView()
// set container frame and add to the screen
self.container.frame = CGRect(x: 60, y: 60, width: 200, height: 200)
self.view.addSubview(container)
// set red square frame up
// we want the blue square to have the same position as redSquare
// so lets just reuse blueSquare.frame
self.redSquare.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
self.blueSquare.frame = redSquare.frame
// set background colors
self.redSquare.backgroundColor = UIColor.redColor()
self.blueSquare.backgroundColor = UIColor.blueColor()
// for now just add the redSquare
// we'll add blueSquare as part of the transition animation
self.container.addSubview(self.redSquare)
Ok, now we need to animate on click for it to look like this.
1
2
3
4
5
6
7
8
9
// ### in click event ###
// create a tuple to hold the views
var views = (frontView: self.redSquare, backView: self.blueSquare)
if self.redSquare.superview == nil {
views = (frontView: self.blueSquare, backView: self.redSquare)
}
let transitionOptions = UIViewAnimationOptions.TransitionCurlUp
UIView.transitionFromView(views.frontView, toView: views.backView, duration: 1.0, options: transitionOptions, completion: nil)