Noah Labhart
Noah Labhart

Reputation: 157

UIWebView in UITableView Cell - WebView not filling Table Cell

I have a table view, with a static cell which has a UIWebView embedded in it. The static cell is in the first and only section, and is the second static cell in the tableview. I am trying to dynamically change the size of the UIWebView AND UITableViewCell, based on the HTML I am passing to the loadHTMLString method. Code below.

Within viewDidLoad:

[self.wbvArticle loadHTMLString:result baseURL:nil];
[self.wbvArticle setDelegate:self];
[self.wbvArticle.scrollView setScrollEnabled:NO];
[self.wbvArticle.scrollView setBounces:NO];

Also have the following:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath     *)indexPath
{
    if (indexPath.row == 1)
    {
        return contentHeightForCell;
    }
    else return 282;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    contentHeightForCell = [[self.wbvArticle stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"] floatValue];

    CGRect rect = self.wbvArticle.frame;
    rect.size.height = contentHeightForCell;
    self.wbvArticle.frame = rect;
    [self.wbvArticle sizeToFit];

    [self.tableView beginUpdates];
    [self.tableView endUpdates];
}

When I run this in the simulator, the table cell is sized correctly, but the webview is not. Does anyone see anything out of the ordinary? I have scoured the web and stackoverflow, but have not been able to find anything to fix it.

Thanks for any help.

Upvotes: 3

Views: 5884

Answers (2)

Kenan Karakecili
Kenan Karakecili

Reputation: 761

Or, you may just use

#pragma mark - WebView Delegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    self.webViewHeight = webView.scrollView.contentSize.height;
    [self.tableView reloadData];
}

Upvotes: 2

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

You need to calculate the height of webview and reload the table with this new height.

1) Create local variable in @interface section

float webViewHeight;

2) Then assign this height in cellForRowAtIndexPath of tableView

[webView setFrame:CGRectMake(0, 0, CELL_CONTENT_WIDTH, webViewHeight)];

3) Also set the height in heightForRowAtIndexPath of tableview

if (indexPath.row == 0) {
    return webViewHeight;
}

4)At last calculate the height and reload tableview

- (void)webViewDidFinishLoad:(UIWebView *)aWebView
{
    CGRect frame = aWebView.frame;
    frame.size.height = 1;
    aWebView.frame = frame;
    CGSize fittingSize = [aWebView sizeThatFits:CGSizeZero];
    frame.size = fittingSize;
    aWebView.frame = frame;
    webViewHeight = fittingSize.height;
    [self.tableView reloadData];
}

Upvotes: 4

Related Questions