Alex Rivera | Logout

iPhone UIView - Resize Frame to Fit Subviews

Asked 2010-08-31T01:11:24.817
42

Shouldn't there be a way to resize the frame of a UIView after you've added subviews so that the frame is the size needed to enclose all the subviews? If your subviews are added dynamically how can you determine what size the frame of the container view needs to be? This doesn't work:

[myView sizeToFit];
Edit
Report

1 Answer

19

It looks like Kenny 's answer above points to the right solution in the referenced question, but may have taken away the wrong concept. The UIView class reference definitely suggests a system for making sizeToFit relevant to your custom views.

Override sizeThatFits, not sizeToFit

Your custom UIViews needs to override sizeThatFits to return "a new size that fits the receiver's subviews", however you wish to calculate this. You could even use the math from another answer to determine your new size (but without recreating the built-in sizeToFit system).

After sizeThatFits returns numbers relevant to its state, calls to sizeToFit on your custom views will start causing the expected resizes.

How sizeThatFits works

Without an override, sizeThatFits simply returns the passed-in size parameter (defaulted to self.bounds.size for calls from sizeToFit. While I only have a couple sources on the issue, it appears that the passed-in size is not to be seen

answered 2012-12-11T21:17:58.810

Your Answer