What can i do to resize a UIView to fit its subviews?

6.7k views Asked by At

I know that i must use -sizeThatFits: method and override it in superView. But, what should I do in this method? should I only calculate new size of my View, or I should send some messages to its subViews? Maybe -sizeThatFits: and -sizeToFit: messages? And, when and how I should "say" to my superView that it is time to Resize its frame?

1

There are 1 answers

3
diegoreymendez On BEST ANSWER

Regarding the first part of your question: Your -sizeThatFits:implementation should never call -sizeToFit:on subviews. The former is a method to calculate a size for your view (without changing it at all), while the latter actually changes your view's size.

You can definitely forward -sizeThatFits: calls to your child views, if that will help in your view's size calculations.

Regarding the second part of your question: you shouldn't be telling your superview when to resize your view, normally. It should be the other way around: a controller or a parent view should be the one to attempt a resize on your child view in the first place.

From Apple's documentation: sizeThatFits - Implement this method if you want your view to have a different default size than it normally would during resizing operations. For example, you might use this method to prevent your view from shrinking to the point where subviews cannot be displayed correctly.

What the docs are saying is that if your -sizeThatFits: implementation never returns a frame below a certain size: that size will basically become your view's minimum size during resize operations.

PS: since in the topic of your question you're asking how to resize a view to fit it's contents - you should be using sizeToFit for that purpose. You'll need to implement that method yourself for custom views.