views:

143

answers:

2

I have a detail page of type UIScrollView. On it I want an optional UIImageView and a mandatory UITextView. If no image is available then the image view should not take any space. The text for the text view can be of varying sizes.

When the view is loaded with, say, the image and the text I need to be able to scroll through all the contents. So the image slips off the top of the screen.

I just can't get this work and I feel it ought to be easy. Any ideas?

A: 

You should create your own view, which inherits after UIScrollView.

In your custom YourScrollView you should overwrite

- (void) layoutSubviews;

There calculate size of the text, size of the image (and additional spacing between then), and then set the contentSize for the scroll view using:

[self setContentSize:CGSizeMake(CGRectGetWidth(self.bounds), yourCalculatedHeight)];

Hope this helps, Paul

Pawel
A: 

You must call setContentSize with the size of the views.

CGRect frameOfImage;
CGRect frameOfText;
CGRect frameOfContent;

frameOfImage.origin = CGPointZero;
frameOfImage.size = myImage ? [myImage size] : CGSizeZero;

[myImage setFrame:frameOfImage];

frameOfText.origin.x = 0;
frameOfText.origin.y = frameOfImage.origin.y + frameOfImage.size.height;
frameOfText.size = [myText.text sizeWithFont:myText.font forWidth:myScroll.bounds.width lineBreakMode:myText.lineBreakMode];

[myText setFrame:frameOfText];

frameOfContent = CGRectUnion( frameOfImage , frameOfText );
frameOfContent.size.height += frameOfContent.origin.y;
frameOfContent.size.width += frameOfContent.origin.x;

[myScroll setContextSize:frameOfContent.size];

You could do the last bit in the layoutSubviews of a custom UIScrollView or all of it at once in your controller when you know whether there is an image or not.

drawnonward