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?
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.
It is not just the size of the receiver is is the potential size size you want to fill. The result is that size that the view believes will best show its contents for the given input size
.
The default behavior is to simply return the size
parameter (i.e. the size that fits the default view is the size you give it)- so yes, this parameter matters by default.
Subclasses could enforce constraints like width==height
or other things like that using this method.