To display several pieces of content on a screen, I needed several views. A scroll view (UIScrollView) was necessary to encompass the headline, photo and story text; I had the headline and photo at the top in a fixed area, but the content was of variable size as the story length changed.
Originally I had a text view (UITextView) to hold the story, but I wanted to do rich-text formatting, and since my database already used HTML to do italic and bold markup, a web view (UIWebView) was the obvious fit.
However, there are some caveats to using web views, most importantly to do with getting the size of the view after you’ve set the content. First, you must make sure the content has completed loading before you retrieve the size; you can do this in the delegate handlerwebViewDidFinishLoading:
Secondly, web views don’t respond correctly to sizeToFit: so you must do some more manual labor using a Javascript call to find the size of the web view after you’ve inserted the content. Some comments on other web sites mentioned that you can try [webView sizeThatFits:CGSizeZero] but this did not work for me.
Here’s the pertinent code from my current project. Also please note that I have a <div id="body"> surrounding my HTML content that I pass into the view. The javascript call uses this to grab the height of the web view after it loads. You’ll also notice that this calculation sometimes falls a little short so I add 12 points to it.
The code below creates a UIButton beneath the text copy, so I added 70 pixels to the contentSize of the enclosing scroll view. It works perfectly for me; hopefully it helps someone else, too.
If there’s a more kosher way to do it, I’d love to hear it. I had considered putting everything (including the headline and photo) inside the UIWebView, but then I would not have been able to have a UIButton beneath/outside it off screen; nor, more importantly would I be able to use my custom NetImageViewer class on the photo. (More on that later.)
#pragma mark -
#pragma mark UIWebViewDelegate methods
-(void)webViewDidFinishLoad:(UIWebView *)webView{
if (webView!=bioWebView)return;
float h;
NSLog(@"web view is %f high", bioWebView.frame.size.height);
NSString *heightString = [bioWebView stringByEvaluatingJavaScriptFromString:@"document.getElementById("body").offsetHeight;"];
NSLog(@"web content is %@ high",heightString);
h = [heightString floatValue] +12.0f; // convert from string to float plus some extra points because calculation is sometimes one line short
bioWebView.frame = CGRectMake(bioWebView.frame.origin.x, bioWebView.frame.origin.y, bioWebView.frame.size.width, h);
// get bottom of text field
h = bioWebView.frame.origin.y + h + 70; // extra 70 pixels for UIButton at bottom and padding.
[scrollView setContentSize:CGSizeMake(320, h)];
/*
position button code here....
*/
}