Craigt
Craigt

Reputation: 3580

Scrollview setcontentsize for dynamic content

How would I go about setting the content size for a scrollview, when the content size is dynamic. I have added all my content to a UIView named "contentView", then try calling the setcontentsize as below, but this results in no scrolling.

sudo'ish code:

[scrollView setContentSize: contentView.frame.size];

Maybe "contentView" is not stretching its size to fit its children?

Any help would be appreciated.

Upvotes: 2

Views: 3194

Answers (3)

Benjamin Mayo
Benjamin Mayo

Reputation: 6679

When you add stuff to your contentView call [contentView sizeToFit] and then the content view will stretch to fit its subviews, then, the code you post will work.

Upvotes: 1

chathuram
chathuram

Reputation: 636

This depends on the type of content you are going to add dynamically. So let's say you have a big text data to show, then use the UITextView and as it is a subclass of the UIScrollView, you can get the setContentSize of TextView when you assign the text content. Based on that you can set the total size of the UIScrollView.

float yPoint = 0.0f;
UIScrollView *myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f, yPoint, 320.0f, 400.0f)];

UITextView *calculatorTextView = [[UITextView alloc] init];
  calculatorTextView.text = @"My looong content text ..... this has a dynamic content";
[calculatorTextView sizeToFit];

yPoint = yPoint + calculatorTextView.contentSize.height; // Bingo, we have the new yPoiny now to start the next component. 

// Now you know the height of your text and where it will end. So you can create a Label or another TextView and display your text there. You can add those components as subview to the scrollview.

UITextView *myDisplayContent = [[UITextView alloc] initWithFrame:CGRectMake(0.0f, yPoint, 300.f, calculatorTextView.contentSize.height)];

myDisplayContent.text = @"My lengthy text ....";
[myScrollView addSubview:myDisplayContent];

// At the end, set the content size of the 'myScrollView' to the total length of the display area.

[myScrollView setContentSize:yPoint + heightOfLastComponent];

This works for me.

Upvotes: 1

Mugunth
Mugunth

Reputation: 14499

UIView or UIScrollView will not auto stretch based on content. You have to manually calculate the frames and position it accordingly inside the scrollview and then set the contentSize of the scrollview to the biggest possible size that can hold all its subviews.

Upvotes: 4

Related Questions