Suhaiyl
Suhaiyl

Reputation: 1081

Adding UIWebView in UITableViewCell

I have a tableview and what i want to do is add the webview on a cell as we click on the cell, plus the height of that particular cell should also adjust as per webview content. Suggestions welcomes.

Upvotes: 2

Views: 4912

Answers (2)

Ishank
Ishank

Reputation: 2926

In the delegate - cellForRowatIndex:, you may do this-

 NSString *HtmlStr = [NSString stringWithFromat:@"<div style=\"font-family:\"Times New Roman\";font-size:18px;\">%@</div>",@"YOUR_String_DATA"];

[cell.webView loadHTMLString:HtmlStr baseURL:nil];

Find the content size(height in your case) using this-

CGSize aSize = [@"YOUR_String_DATA" sizeWithFont:@"Times New Roman" minFontSize:18.0f actualFontSize:18.0f forWidth:TableViewCellWidth lineBreakMode:lineBreakMode];

cell.webView.frame = CGRectMake(0,0,aSize.width,aSize.height);

Also, in the heightForRowatIndex: delegate method u have to somehow return the height aSize.height

Upvotes: 0

Mani
Mani

Reputation: 571

It depends on the number of cells in which you have a web view. Ideally, you would have to wait for the web view to render and then change the height of the web view and the cell

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *string = [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"body\").offsetHeight;"];
    CGFloat height = [string floatValue] + 8;
    CGRect frame = [_webView frame];
    frame.size.height = height;
    [_webView setFrame:frame];

//Store the height in some dictionary and call [self.tableView beginUpdates] and [self.tableView endUpdates]
}

Of course, this would take a bad perfomance hit, but for a single cell this is not bad.If in case more than one cell has a web view , go with Ishank's approach. However if your string contains div elements like <td> the method will return a misleading height.

Upvotes: 2

Related Questions