4

In the question "When does layoutSubviews get called?" several cases are listed:

  1. The parent view is resized
  2. The device is rotated
  3. Any more?

If there is no requirement to handle, for UITableView, we can create a header view for the section header by creating one customized UIView. The simplest way is to create the UIView by initWithFrame: and then there is no need to relayout any more.

Therefore, in my opinion, we do not need override layoutSubviews etc. But there are some opinions to insist overriding it.

Reasons to not use it:

  1. KISS (keep it simple and stupid )
  2. No requirement for relayout
  3. Relayout has cost when scrolling

My question here is to get more suggestions for this case. Thanks.

Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
Forrest
  • 122,703
  • 20
  • 73
  • 107

1 Answers1

4

You don't usually need to override layoutSubviews. There are basically only two reasons:

  • Your custom UIView subclass has subviews that you want to rearrange using manual layout
  • Your custom UIView subclass needs to know when its size changes for some other reasons, like shrinking a font size or doing some manual drawing

Generally speaking, you don't need to override this method. Most layout is done either by the view controller setting the view's frame at appropriate times, or by using auto-layout.

Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
  • I still cant figure out how to use the 'manual layout' inside layoutSubviews properly. Do you always use a flag like 'layoutDone' or do you calculate it every time the method is called ? How do you keep constraints from being added multiple times to the view ? – Petar Apr 23 '16 at 09:53
  • 1
    @petar No, never use a flag and never add constraints there. This method must be indempotent. You just set frames in that method. – Aaron Brager Apr 23 '16 at 12:20
  • So if I have a view which gets dynamically updated (e.g. I want to add a subview to a particular location, or rearrange currently added subviews, etc) - where should this happen ? Say I initialize a custom view which contains a set of model objects that I want to be displayed when the view is added to a superview. (Initially the view won't know its correct size and the layout of the model objects cant happen properly) - where should this happen you think ? Many thanks – Petar Apr 23 '16 at 13:22
  • You should post a new question – Aaron Brager Apr 23 '16 at 14:52