Changes:
Delete function updateOffScreenLabel() and any statements that reference it.
override func viewDidLoad() {
super.viewDidLoad()
currentQuestionLabel.text = questions[currentQuestionIndex]
// Disable current centerX constraint of nextQuestionLabel
nextQuestionLabelCenterXConstraint.isActive = false
// Create a UILayoutGuide instance between the centerXs of the two labels
let spaceBetweenLabels = UILayoutGuide()
self.view.addLayoutGuide(spaceBetweenLabels)
spaceBetweenLabels.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
nextQuestionLabel.centerXAnchor.constraint(equalTo: spaceBetweenLabels.leadingAnchor).isActive = true
currentQuestionLabel.centerXAnchor.constraint(equalTo: spaceBetweenLabels.trailingAnchor).isActive = true
}
The x centers of the two labels are linked to the leading and trailing edges of the UILayoutGuide instance. When the currentLabel has moved from center to right outside the view, the nextLabel has moved from left side outside the view to center of the view.
When the animation is completed, the constant of the currentLabel x constraint is set to zero. The currentLabel will be at center of the view and nextLabel will be at one screenwidth left of currentLabel.
func animateLabelTransitions() {
// Force any outstanding layout changes to occur
view.layoutIfNeeded()
// Animate the alpha
// and the center X constraints
let screenWidth = view.frame.width
self.currentQuestionLabelCenterXConstraint.constant += screenWidth
UIView.animate(withDuration: 0.5, delay: 0, options: [.curveLinear],
animations: {
self.currentQuestionLabel.alpha = 0
self.nextQuestionLabel.alpha = 1
self.view.layoutIfNeeded()
},
completion: { _ in
self.currentQuestionLabel.text = self.nextQuestionLabel.text
self.currentQuestionLabel.alpha = 1
self.currentQuestionLabelCenterXConstraint.constant = 0
self.view.layoutIfNeeded()
self.nextQuestionLabel.alpha = 0
})
}