Dynamic height for uiwebview with html data

533 views Asked by At

As part of my applications i need to display html contents in uiwebview and the data conatins <ul> and <li> tags i am using the attributed string for calculating the height of the webview but whenever data comes with this listed contents it will calculate incorrect height i am stuck with this issue for lat 2 days, when the list contain short text data then it will returns less heights and my contents will misssed when it comes to ipad the issue became worst because of the large width of the webview.

screenshots screenshots

 NSMutableAttributedString *htmlString1 =
        [[NSMutableAttributedString alloc] initWithData:[[self.doctorDetail objectForKey:@"Description"] dataUsingEncoding:NSUTF8StringEncoding]
                                                options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                          NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]}
                                     documentAttributes:NULL error:nil];

        [htmlString1 addAttributes:attrsDictionary range:NSMakeRange(0, htmlString1.length)];
        CGSize discriptionsize = CGSizeMake(self.discriptionLabel.frame.size.width, FLT_MAX);


        CGRect textRect = [htmlString1 boundingRectWithSize:discriptionsize options:NSStringDrawingUsesLineFragmentOrigin context:nil];

CGSize expectedLabelSize = CGSizeMake(textRect.size.width, textRect.size.height);
[self.discriptionLabel setFrame:CGRectMake(self.discriptionLabel.frame.origin.x, self.doctorImage.frame.origin.y+self.doctorImage.frame.size.height+5, self.discriptionLabel.frame.size.width, expectedLabelSize.height+10)];
2

There are 2 answers

0
Anshad Rasheed On BEST ANSWER

I got the trick,

just replaced the <li> with <br> before setting it to attributed string

   valueString = [valueString stringByReplacingOccurrencesOfString:@"<li>" withString:@"<br>"];
0
Nils Ziehn On

You should probably do something like this:

- (void)viewDidLoad
{
    [super viewDidLoad];
    webview.delegate = self;
    [webview loadHTMLString:@"<div id='foo' style='background: red'>The quick brown fox jumped over the lazy dog.</div>" baseURL:nil];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *output = [webview stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"foo\").offsetHeight;"];
    NSLog(@"height: %@", output);
}

Thx for the answer provided here: http://stackoverflow.com/a/751326/1816644