2

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.

4

2 回答 2

8

来自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);

这是一种很好且简单的方法。

于 2013-09-13T04:12:53.187 回答
1

斯威夫特 2.0 版本

    var sizeOfContent: CGFloat = 0
    let lLast: UIView = scrollView.subviews.last!
    let wd: CGFloat = lLast.frame.origin.y
    let ht: CGFloat = lLast.frame.size.height
    sizeOfContent = wd + ht
    scrollView.contentSize = CGSizeMake(scrollView.frame.size.width, sizeOfContent)
于 2016-01-24T18:52:04.997 回答