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:
- The view has a height of 0.
- The view has a subview whose height is 10
- After sizetofit, nothing change. How come?
I can compute the frame directly however, this bothers me.
When you call the
sizeToFitmethod on a view, it ends up calling thesizeThatFits:method on the view. The default implementation ofsizeThatFits: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 callsizeToFit.This is all spelled out in the docs for
UIView sizeToFitandUIView sizeThatFits:.Classes like UILabel do implement
sizeThatFits:to return an appropriate size.