Search code examples
iosios6uiscrollviewscrollview

UIScrollview Dynamic content size is very off based on number of items


I have a vertical scrollview with thumbnail images to act as a "side panel" for specific items on an ipad app.

Here's my code to set the content size:

- (void)setScrollViewContentSize:(UIScrollView*)scrollView{
    NSInteger viewCount = [scrollView.subviews count];

    NSLog(@"viewCount: %d", viewCount);
    NSLog(@"height: %f", (viewCount * 190.0f));
    scrollView.contentSize = CGSizeMake( scrollView.superview.frame.size.width, (viewCount * 190.0f));
    }

When I run my app, there's one menu that has 57 items, so the viewCount log shows up as 57 and the height shows up as 10830. On another menu, I have 13 items and thus, the height is 2470.

Everything seems fine here, but when I scroll to the end of the view, the menu with 57 icons has way too much white space left over whereas the menu with 13 items ends perfectly on the last item with a little margin (each thumbnail is 183px). I'm trying to find out what the cause is, but it seems like the more menu items I have, the bigger the scroll view's spacing at the last item gets.

I tried calling scrollView sizeToFit and even trying to create a CGRect of a visible region to apple to my frame, but none of those worked. Any ideas?

thank you.


Solution

  • from https://stackoverflow.com/a/14852596/1363779

    float sizeOfContent = 0;
    UIView *lLast = [scrollView.subviews lastObject];
    NSInteger wd = lLast.frame.origin.y;
    NSInteger ht = lLast.frame.size.height;
    
    sizeOfContent = wd+ht;
    
    scrollView.contentSize = CGSizeMake(scrollView.frame.size.width, sizeOfContent);
    

    This is a nice and easy way to do it.