开发者

UIWebView document stays height of tallest content

I'm loading content into a UIWebView with the following call:

NSString *detailHtmlString = [NSString stringWithFormat:@"<html><head><style>body {background: black;color: white;line-height: 1.4em; font-family: sans-serif; margin: 0; padding: 0 0 30px 0;width: 280px;} p {margin-top: 10px;}</style></head><body id=\"content\">%@</body></html>",[currentWeek objectForKey:@"post_content"]];
[weekDetailController.movie_detail loadHTMLString:detailHtmlString baseURL:nil];

Then, after it it finishes loading:

- (void) webViewDidFinishLoad:(UIWebView *)sender {
    [self performSelector:@selector(calculateWebViewSize) withObject:nil afterDelay:0.1];
}

- (void) calculateWebViewSize {

    [weekDetailController.movie_detail sizeToFit];
    float newHeight = [[weekDetailController.movie_detail stringByEvaluatingJavaScriptFromString :@"document.getElementById(\"content\").offsetHeight"] floatValue];


    newHeight += 300; //height of the other elements
    NSLog(@"Height: %f",newHeight);

    CGRect frame = weekDetailController.movie_detail.frame;

    NSLog(@"Height was: %f",frame.size.height);

    frame.size.height = newHeight;

    weekDetailController.movie_detail.frame = frame;

    [scrollView.scrollView setContentOffset:CGPointZero];
    [scrollView.scrollView setContentSize:CGSizeMake(frame.size.width, frame.size.height)];
}

This works great the first time the view is loaded, but on subsequent views, when different content has been loaded into the UIWebView (using the same call as above), the JavaScript call to get the height returns larger and larger values -- even if the content is smaller, it still returns the height of the largest amount of content that had been in the 开发者_运维问答view at some point. I've tried loading a blank HTML string into the view to "clear" it, but that doesn't seem to help either.

Any hints would be appreciated!


[scrollView.scrollView setContentOffset:pt];
[scrollView.scrollView setContentSize:CGSizeMake(frame.size.width, frame.size.height)];

Are you using nested UIScrollViews? It could be that you are only setting the size of the inner scroll view and leaving the outer scroll view to the largest size it's content has been.

Edit:

Also you should just use [scrollView.scrollView setContentOffset:CGPointZero];


When using nested UIWebViews with Constraints, you need to reset the constraint (e.g. to 1) and reload the webview afterwards:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, coordinator.transitionDuration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    self.webViewHeightConstraint.constant = 1;
    [self reloadWebView]; //[self.webview reload] doesn't work here, simply load with the given url or given html content
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜