This question follows up on Removing HTML url tags in iOS. I have decided to go with the Web View approach, because it seems like that's the easiest way to get proper links (aka links with actual titles, instead of just the url). But I'm stuck on how to calculate the height of the web view. I use table view cells with web views as subviews.
My current, failing approach:
The table view asks for the height of the cell
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [CommentTableViewCell heightForCellWithComment:(self.comments)[indexPath.row]];
}
This works well with a text view, because I can just use boundingRectWithSize:options:attributes:context:
to calculate the text height, add some padding on the top and bottom, and return the height. With a web view, I can't do this. I currently take the data returned from the web, which still contains some html tags, insert some html to change the font etc, and then render it in a web view. If I'd use an approach like boundingRectWithSize:options:attributes:context
: the returned height is obviously way off.
This could tries to calculate the height, but that doesn't work and returns 0. The body
property on the commment
contains the html data.
+ (CGFloat)heightForCellWithComment:(Comment *)comment
{
CommentTableViewCell *cell = [[CommentTableViewCell alloc] init];
[cell.textWebView loadHTMLString:comment.body baseURL:nil];
cell.textWebView sizeThatFits:
CGSizeMake(cell.textWebView.frame.size.width, CGFLOAT_MAX)];
return cell.textWebView.frame.size.height + 48.0f; // 48 px padding
}
UITableViewDataSource asks for cell. I dequeue a cell from the storyboard, and set a comment
property on it.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:...];
Comment *comment = ...;
cell.comment = comment;
return cell;
}
So what I'd say I'm looking for is a way to calculate the web view's dimensions before all the table view stuff kicks in. Thank you in advance.
Loading the HTML string is done asynchronously. You have to set a delegate for the UIWebView
and wait for the webViewDidFinishLoad:
call. In this call you can query the web view for its height by accessing the webView.scrollView.contentSize.height
. Then you can store the height and tell the table view to reload the particular cell, it will then have the correct height.