UIWebview框架没有调整其内容的大小

时间:2013-05-23 08:17:41

标签: iphone ios objective-c uitableview uiwebview

我的NSString包含HTML tags。所以为了正确显示我正在使用UIWebview。现在我想调整UIWebview的框架大小以适应内容。我将此UIWebview添加到tableHeader。现在这就是我的工作。

在我的viewDidLoad

UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(10, height2,self.view.bounds.size.width-30, 20)];
    [[webView scrollView] setBounces: NO];
    webView.delegate = self;
    [self.headerView addSubview:webView];

    [self setWebDescription:webView];

然后在setWebDescription

-(void)setWebDescription:(UIWebView *)webDescription
{
    NSString *myDescriptionHTML = [NSString stringWithFormat:@"<html> \n"
                                   "<head> \n"
                                   "<style type=\"text/css\"> \n"
                                   "body {font-family: \"%@\"; font-size:15; font-color:\"%@\";}\n"
                                   "</style> \n"
                                   "</head> \n"
                                   "<body>%@</body> \n"
                                   "</html>",@"TeutonNormal",@"#AAAAAA", _newsItem.new_body];
    [webDescription setBackgroundColor:[UIColor clearColor]];
    [webDescription setOpaque:NO];
    [webDescription loadHTMLString:myDescriptionHTML baseURL:nil]; 
}

最后在我的webViewDidFinishLoad

- (void)webViewDidFinishLoad:(UIWebView *)aWebView {
    CGRect newBounds = aWebView.bounds;
    [aWebView sizeToFit];
    newBounds.size.height = aWebView.scrollView.contentSize.height;
    aWebView.bounds = newBounds;
    aWebView.scrollView.bounds = newBounds;
    aWebView.contentMode = UIViewContentModeRedraw;

    NSLog(@"Height is %f",newBounds.size.height);

    newHeight =  height2 + aWebView.frame.size.height;


    UILabel *lblLikes = [[UILabel alloc]initWithFrame:CGRectMake(40, newHeight+10, 160, 40)];
    lblLikes.text = _newsItem.new_publishdate;

    float newHeight2 =  newHeight + 80;
    NSLog(@"new height header is %f",newHeight2);
    [self.headerView setFrame:CGRectMake(0,0,self.view.bounds.size.width,newHeight2)];
        [headerView addSubview:lblLikes];

    [self.tableView setBounces:NO];
    self.tableView.tableHeaderView = headerView;

我还在webview下面添加了另一个标签。现在问题是我的webview总是像我在viewDidLoad中设置的那样高20px。所以它不符合内容。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:2)

您可以使用以下类型获取UIWebView

的内容高度
CGFloat newHeight = [[self.answerWebView stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollHeight;"] floatValue];

希望它会帮助你......