So I'm learning how to make views animate from out of screen, to use as slider-menus.
class ViewController: UIViewController {
@IBOutlet weak var red: UIView!
@IBOutlet weak var redHConstraint: NSLayoutConstraint!
@IBAction func buttonShift(sender: AnyObject) {
self.view.layoutIfNeeded() // **HERE**
UIView.animateWithDuration(0.5) {
self.redHConstraint.constant = 0
self.view.layoutIfNeeded() // And **HERE**
}
}
}
i've adapted this code from How to animate a UIView with constraints in Swift?
1. What does self.view.layoutIfNeeded()
part of the code do?
2. Why is it coded 2x, before and during animation?
Note: if i comment-out the 1st self.view.layoutIfNeeded()
nothing changes, but if i comment-out the 2nd self.view.layoutIfNeeded()
the movement is no longer animated and just appears in the new coordinates.
layoutIfNeeded()Lays out the subviews immediately, if layout updates are pending.
— layoutIfNeeded() In contrast, the method layoutIfNeeded is a synchronous call that tells the system you want a layout and redraw of a view and its subviews, and you want it done immediately without waiting for the update cycle.
layoutSubviews() The system calls this method whenever it needs to recalculate the frames of views, so you should override it when you want to set frames and specify positioning and sizing. However, you should never call this explicitly when your view hierarchy requires a layout refresh.
Invalidates the current layout of the receiver and triggers a layout update during the next update cycle. iOS 2.0+ iPadOS 2.0+ Mac Catalyst 13.0+ tvOS 9.0+
Essentially calling the self.view.layoutIfNeeded()
will force the layout of self.view
and its subviews if some change set setNeedsLayout
for self.view
.
setNeedsLayout
is used to set a flag that whenever layoutIfNeeded()
is called, layoutSubviews
will then be called. It is what determines the "if needed" aspect of the call.
If you make a change to UIView which causes it to setNeedsLayout
but layoutIfNeeded()
is not called (therefore layoutSubviews is not called) it will not update and therefore could cause issues with your animation. If you call it before hand it will ensure that if there was a change that needed your layout to be updated then it will apply it to your view and all of its subviews before animating.
And of course, when animating you are making changes which need to be updated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With