Harry Lawrence
Harry Lawrence

Reputation: 833

How can I get a UIScrollView to scroll vertically with dynamic amount of subviews inside of it?

So I have a UIScrollView and within that, I'd like to add some subviews, currently I have around 5 or 6, they are about 90px in height, so obviously when it gets to the bottom of the screen, I'd like it to scroll so you can see more, if that makes sense.

Below is what I have already, parentView being the UIScrollView, newResult being a row I'd like to append. GSResultBlock is a class that extends UIView.

    for (NSObject * person in resultsCollection) {
      CGRect resultBlockFrame   = CGRectMake(0, resultCount, parentView.bounds.size.width, 90);
      GSResultBlock * newResult = [[GSResultBlock alloc] initWithFrame:resultBlockFrame];

      [parentView addSubview:[newResult getResultBlock]];

      [newResult release];

      resultCount = resultCount + 95;
}

Keep in mind that foreach newResult there will be additional subviews in there also, for example, a UIImageView ect.. (They are not included in the code above though)

Any ideas? Thanks in advance.

Upvotes: 0

Views: 777

Answers (2)

Fonix
Fonix

Reputation: 11597

have a look at this answer

float maxHeight = 0;

for(UIView *v in [scrollView subviews]){
    if(v.frame.origin.x + v.frame.size.height > maxHeight)
        maxHeight = v.frame.origin.x + v.frame.size.height;
}

self.scrollView.contentSize = CGSizeMake(scrollView.frame.size.width, maxHeight+5);

once you have put all your views into the scroll view, run this and it will make your scrollview scroll the right amount

Upvotes: 0

Aaron Golden
Aaron Golden

Reputation: 7102

You need to update the contentSize of the UIScrollView using something like:

[parentView setContentSize:CGSizeMake(CGRectGetWidth(parentView.frame), resultCount)];

after the end of your for loop.

Upvotes: 2

Related Questions