Struggling to Understand the Relationship Between Frame Size and Viewport Size in UIWebView

iOS
2015-09-11 18:53 (9 years ago) ytyng

iOS Simulator 8.4

Here's how to create a UIWebView that's slightly smaller than the screen,

CGSize displaySize = screenSize;
int leftOffsetPercent = 5;
int topOffsetPercent = 5;

CGRect webViewFrame = CGRectMake(
        displaySize.width / 100 * leftOffsetPercent,
        displaySize.height / 100 * topOffsetPercent,
        displaySize.width / 100 * (100 - leftOffsetPercent * 2),
        displaySize.height / 100 * (100 - topOffsetPercent * 2)
);
self.webView = [[UIWebView alloc] initWithFrame:webViewFrame];

When I loaded and displayed an HTML with a ViewPort Meta specified like this:

<meta name="viewport" content="width=device-width, initial-scale=1">

A horizontal scroll bar appeared, and the content did not fit within the WebView.

Since it's an iPhone 6, displaySize.width is 375, and webView.frame.size.width is 337.5. It seems that the viewport's device-width is judged to be this 375.

Out of curiosity, when I obtained window.innerWidth within the browser, it was 338, but when I checked document.body.clientWidth, it was 375. I couldn't understand why this was happening.

I was puzzled about how to remove the horizontal scroll bar, but in the end, I tried dynamically rewriting the meta tag in the HTML as follows:

var viewPortMeta = $('meta[name="viewport"]');
viewPortMeta.attr('content', "width=" + (window.innerWidth - 1) + ", initial-scale=1");

Although I think it's a rather forceful method, it worked. The horizontal scroll bar disappeared.

Currently unrated

Comments

Archive

2025
2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011