I am making use of the UIWebView
to render some HTML. However, although the width of my webview is 320 my HTML is still shown full width and can be scrolled hor
Just add this:
webView.scalesPageToFit = YES;
Typically, you should use the viewport meta tag. But its use is very erratic, mostly if you want a cross platform web page.
It also depends of what content and css you have.
For my iPhone homepage, which must auto-resize from portrait to lanscape, I use this :
<meta name="viewport" content="width=device-width; minimum-scale=1.0; maximum-scale=1.0; user-scalable=no">
If you need special resize, you can also use the event :
<body onorientationchange="updateOrientation();">
with the corresponding funciton in your javascript :
function updateOrientation() {
if(Math.abs(window.orientation)==90)
// landscape
else
// portrait
}
EDIT :
Seeing you page source, it seems you made it with a web editor, don't you ?
Ok, I understand. Your main div has a width of 600px. The iphone screen resolution is 320x480. 600 > 320 so it exceeds the screen bounds.
Now, let's make some simple operations:
320 / 600 = 0.53
480 / 600 = 0.8
So you want to zoom out 0.5 times minimum and 0.8 times maximum. Lets change the viewport :
<meta name="viewport" content="width=device-width; minimum-scale=0.5; maximum-scale=0.8; user-scalable=no">
i solved the issue by unticking "scales page to fit"
You may generate an NSAttributedString
from HTML (do it on background):
@implementation NSAttributedString (Utils)
+ (void)parseHTML:(NSString *)html withCompletion:(void (^)(NSAttributedString *completion, NSError *error))completion
{
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
NSError * __autoreleasing *error = nil;
NSAttributedString *result = [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
documentAttributes:nil error:error];
NSError *safeError = (error != nil) ? *error : nil;
dispatch_sync(dispatch_get_main_queue(), ^(void){
completion(result, safeError);
});
});
}
@end
And show it through UITextView
instance:
[NSAttributedString parseHTML:htmlString withCompletion:^(NSAttributedString *parseResult, NSError *error) {
bodyTextView.attributedText = parseResult;
}];
Some layout features, though, may corrupt with this approach.
@implementation UIWebView (Resize)
- (void)sizeViewPortToFitWidth {
[self stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.querySelector('meta[name=\"viewport\"]').setAttribute('content', 'width=%d;', false); ", (int)self.frame.size.width]];
}
@end
What worked for me was to select the UIWebView in Interface Builder and check the box that says "Scales Page To Fit":