8

According to the documentation for -[UIView setNeedsLayout]:

Because this method does not force an immediate update, but instead waits for the next update cycle, you can use it to invalidate the layout of multiple views before any of those views are updated. This behavior allows you to consolidate all of your layout updates to one update cycle, which is usually better for performance.

Sounds great - but when I use setNeedsLayout without then calling layoutIfNeeded, I find that my control doesn't lay itself out. I had hoped that an "update cycle" would happen before the control was next shown, but I guess that isn't how it works. So what is an "update cycle"? When does one happen?

Simon
  • 25,468
  • 44
  • 152
  • 266

4 Answers4

3

The 'update cycle' happens at the end of the current run loop cycle.

setNeedsLayout must be called on the main thread (main runloop).

Nick Dowell
  • 2,030
  • 17
  • 17
0

That's strange, I use a lot of custom drawn stuff that I change and call "[self setNeedsLayout]" a lot and I never had to call "layoutIfNeeded"...

Are you sure your "drawRect" is fine and not having some problem? Maybe its data isn't ready before you call "setNeedsLayout".

The first answer to the following thread could help you further.

Community
  • 1
  • 1
Bersaelor
  • 2,517
  • 34
  • 58
  • we haven't overridden drawRect at all - the question is about layout of subviews, not rendering of the view itself. – Simon Jul 01 '12 at 08:19
  • Huh, oh then sorry for slightly going in the wrong direction. Usually this method is associated with the drawRect-Overwriting. Are you using several nested Viewcontrollers? (Because that was discouraged till iOS 5). Also you might be interested in the [Understanding UIKit Rendering lecture](https://developer.apple.com/videos/wwdc/2011/) in the 2011 wwdc, maybe that will help with some insights. – Bersaelor Jul 01 '12 at 10:51
  • We're not using anything iOS-5 specific. I'll have a look at the lecture, but my question is still about layout, not rendering - is there a lecture about layout anywhere? – Simon Jul 01 '12 at 11:21
-1

I don't think there is such an evident bug in UIKit. Being you, I would check if my code calls all base methods I overrided. Especially, in hierarchy parents of the problematic object. If this doesn't help, I would replace custom parent view with some standard views to see if the problem persists. This would help to isolate the problem.

Ivan Nikitin
  • 3,578
  • 27
  • 39
-2

Use layoutIfNeeded instead, which triggers immediate layout update.

setNeedsLayout just schedules layout to the handler, being executed until the next update cycle. refer to: http://www.iosinsight.com/setneedslayout-vs-layoutifneeded-explained