QuartzCore provides a CATransition
class for animated transition operations. CATransition
has the following definition:
The CATransition
class implements transition animations for a layer. You can specify the transition effect from a set of predefined transitions or by providing a custom CIFilter
instance.
In order to have your label's text transition animated by pushing upwards the old text, you'll have to create an instance of CATransition
and set its type
to kCATransitionPush
and its subtype
to kCATransitionFromTop
:
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animation.type = kCATransitionPush
animation.subtype = kCATransitionFromTop
animation.duration = 1
You will then be able to animate your label's text transition by adding the animation to your label's layer:
label.layer.add(animation, forKey: nil)
label.text = "Some new content"
The following Swift 3 Playground code shows a possible implementation in order to animate a UILabel
's text transition using CATransition
:
import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
let label: UILabel = {
$0.frame.origin = CGPoint(x: 50, y: 50)
$0.text = "Bob"
$0.sizeToFit()
return $0
}(UILabel())
let animation: CATransition = {
$0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
$0.type = kCATransitionPush
$0.subtype = kCATransitionFromTop
$0.duration = 1
return $0
}(CATransition())
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(label)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(toggle(_:)))
view.addGestureRecognizer(tapGesture)
}
func toggle(_ sender: UITapGestureRecognizer) {
label.layer.add(animation, forKey: nil)
label.text = label.text == "Bob" ? "Dan" : "Bob"
label.sizeToFit()
}
}
let controller = ViewController()
PlaygroundPage.current.liveView = controller