2

I have to display a few views in a UIScrollView and I want it to fit the subviews. Are there any methods that could help me? It doesn't seem hard for a UIView to resize itself according to its children but I can't find any method do such a thing. I don't know before the execution the width and the height of all my subviews as well as how many subviews I'll have.

My first idea is to create a category for the UIView or UIScrollView that will define the maximum of all subview height and width like that:

maxHeight = (subview.frame.origin.y + subview.frame.size.height)

Then when I have the width and the height that will fit all my subviews, I can perform a setContentSize on my UIScrollView. I expect that a method should already exist for that.

A solution:

@implementation UIScrollView (autoResizeContent)

- (void) resizeContentFromSubviews{

    float maxWidth = 0;
    float maxHeigt = 0;

    float height, width;

    for (UIView* v in self.subviews) {
       height = (v.frame.size.height+v.frame.origin.y);
       if(height > maxHeigt ){
           maxHeigt = height;
       }
       width = (v.frame.size.width + v.frame.origin.x);
       if(width > maxWidth){
           maxWidth = width;
       }
    }

    [self setContentSize:CGSizeMake(maxWidth, maxHeigt)];
}
@end
bneely
  • 9,083
  • 4
  • 38
  • 46
Benjamin Ellis
  • 171
  • 1
  • 7

0 Answers0