Brendon Cheung
Brendon Cheung

Reputation: 1035

iOS layout pass and constraints update

From the apple documentation, under the deferred layout pass, it says

'Instead of immediately updating the affected views’ frames, Auto Layout schedules a layout pass for the near future. This deferred pass updates the layout’s constraints and then calculates the frames for all the views in the view hierarchy.'

What is really baffling is the term "near future".

The function setneedsLayout() signals that you want to redraw a view and all of its subviews, when it is time for an update cycle, but why even bother calling this function when you don't even know when the update cycle will happen? shouldn't we just use layoutIfNeeded() all the time so that we can say in our heads that "right, I want this view to be updated now, so I'll use layoutIfNeeded(). Also, is there any other uses of layoutIfNeeded() other than using it in UIView.animateWithDuration()?

I've been reading a lot of article and the concept still hasn't really stick yet, thanks guys

Upvotes: 1

Views: 1062

Answers (1)

Brandon A
Brandon A

Reputation: 8279

You do not need to call the setNeedsLayout() directly most of the time. When you make a change to a UIView it will automatically call setNeedsLayout. When you update constraints in Auto Layout it will send the deferred pass message to the affected UIViews that it will need to that they need to layout as well. This will mark the view as needing to layout it's subviews. You can layout the view at a certain time by calling the layoutIfNeeded() function. This will execute and layout the subviews as required.

As you asked, there are many more uses to called the layoutIfNeeded() function without calling it inside an animation block.

For a simple example, maybe you don't want to use animations at all, and just want to layout your constraints.

subview.frame = CGRect(x: 100, y: 100, width: 50, height: 50) 
// Above makes change to the view. 'setNeedsLayout()' has been called

// Below will layout immediately
view.layoutIfNeeded() 

To answer you question about the "near future" portion, I am not entirely sure. An educated guess would be that because all of the affected UIViews in the layout change have to be informed to layout at a certain time that would mean they would also need to calculate their new frames. Depending on the amount of UIViews that invoke the setNeedsLayout() function there could be some significant processing time involved. And that maybe be why they say in the "near future".

Upvotes: 1

Related Questions