Question

Let's examine this line of codes (only 1 actually change anything)

PO(self.containerForFormerHeader);
PO(self.containerForFormerHeader.subviews);
[self.containerForFormerHeader sizeToFit];
PO(self.containerForFormerHeader);

Result:

self.containerForFormerHeader: <UIView: 0x8b669c0; frame = (0 75; 320 0); autoresize = W+H; layer = <CALayer: 0x8b5eb30>>
self.containerForFormerHeader.subviews: (
    "<UIImageView: 0xd572210; frame = (0 0; 320 10); autoresize = LM+RM+TM; userInteractionEnabled = NO; layer = <CALayer: 0xd572250>> - shading-top-Table.png"
)
self.containerForFormerHeader: <UIView: 0x8b669c0; frame = (0 75; 320 0); autoresize = W+H; layer = <CALayer: 0x8b5eb30>>

From the result it's obvious that:

  1. The view has a height of 0.
  2. The view has a subview whose height is 10
  3. After sizetofit, nothing change. How come?

I can compute the frame directly however, this bothers me.

Was it helpful?

Solution

When you call the sizeToFit method on a view, it ends up calling the sizeThatFits: method on the view. The default implementation of sizeThatFits: returns the view's current size.

So unless your custom view explicitly overrides the sizeThatFits: method to return an appropriate size to contain its subviews, nothing will change size when you call sizeToFit.

This is all spelled out in the docs for UIView sizeToFit and UIView sizeThatFits:.

Classes like UILabel do implement sizeThatFits: to return an appropriate size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top