Reputation: 5477
I get HTML string in UTF-8 Format and I need to display it in a webView. But I want the string to be centred both horizontally as well as vertically in the UIWebView
Upvotes: 1
Views: 367
Reputation: 5477
Well I tested and worked out a working solution. Well here is how I achieved the desired output. Well the function calculateHeight is written by me. I came across different solutions but none of them gave the desired solution for vertical centring. The method calculateHeight returns the total height of the NSAttributedString which would be generated on converting the HTML text to NSAttributedString. This height value is further used to centre the text vertically by providing the required padding.
//subCatTexts.text contains the HTML String
NSString *myHTML = [NSString stringWithFormat:@"<!DOCTYPE html><html><head><style>.center
{padding: %fpx 0;border: 0px solid green;text-align: center;}</style></head><body><div class=\"center\"><p>%@</p></div></body>
</html>",self.webView.frame.size.height/2.0-[self calculateHeight:subCatTexts.text],subCatTexts.text];
[_webView loadHTMLString:myHTML baseURL:nil];
The function used is defined here
- (float) calculateHeight:( NSString *)html
{
const char *c = [html cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:c length:strlen(c)];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSAttributedString *attributedString = [[NSAttributedString alloc]
initWithData: [string dataUsingEncoding:NSUnicodeStringEncoding]
options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
documentAttributes: nil
error: nil
];
//-------------Calculating the height of the attributed String-----
CGFloat width = self.view.frame.size.width; // whatever your desired width is
CGRect rect = [attributedString boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
return (rect.size.height);
}
Upvotes: 1