Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why need override layoutSubviews

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.

like image 782
Forrest Avatar asked Nov 02 '25 02:11

Forrest


1 Answers

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.

like image 169
Aaron Brager Avatar answered Nov 03 '25 20:11

Aaron Brager



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!