Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone -- the input parameter to UIView's sizeThatFits method

Tags:

iphone

uiview

The signature of this method is:

- (CGSize)sizeThatFits:(CGSize)size 

I don't understand what the size parameter is used for. Apple's documentation states that it is "The current size of the receiver."

But the receiver presumably knows its current size. So why does it need to be passed in?

When I experimentally pass in other values, the method appears to use the receiver's current size anyway.

Can anyone explain? And is there any case where this parameter matters?

like image 643
William Jockusch Avatar asked Oct 25 '10 15:10

William Jockusch


Video Answer


1 Answers

First of all, this method is AppKit legacy (not in the negative sense of the word).

Yes, any view has some current size at any given moment and can retrieve it from the bounds property. But there are tricky situations during layout when the best size depends on not-quite-static factors. Take a text label, for example. It may be flowed in one or more lines and the number of lines may depend on the maximum allowed width. So a possible UILabel implementation could derive its bounds size from the width of the CGSize passed to sizeThatFits:, in which case that size is not literally the current size of the receiver, but some desired/limit size.

Thus any UIView subclass can implement -sizeThatFits: as it sees fit (pun intended), and is even free to ignore the size parameter. Most often when I have to implement this method, I ignore it because I can calculate it from the internal state of the view, but in a more complex scenario you might need to use the size parameter to hint yourself about certain restrictions in layout.

like image 74
Costique Avatar answered Sep 22 '22 19:09

Costique