Strange padding/margin when using UIWebView

2020-02-04 06:59发布

I am creating an app that is having a UIWebView which contains an advert. The size of the view is the same as the advert (image) itself. Still, there is a white margin/padding of some kind above and to the left of the image, inside the UIWebView. Check out the linked image:

alt text

Actually, the image is pushed down and to the right due to this padding also.

Any idea how I should remove the white padding?

Thanks in advance!

3条回答
smile是对你的礼貌
2楼-- · 2020-02-04 07:32

I know this is an old post, but just in case anyone is having the same issues. I was able to fix the same issue by adding the following code into the webViewDidFinishLoad delegate method.

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *padding = @"document.body.style.margin='0';document.body.style.padding = '0'";
    [webView stringByEvaluatingJavaScriptFromString:padding];
}

Look at the first banner with the above code added. And the bottom one without the code.

enter image description here

查看更多
Rolldiameter
3楼-- · 2020-02-04 07:43

Basically, all browsers add in that whitespace around the edges of the page to be backwards-compatible with like Netscape 1. In the HTML you're loading into the web view, you can use CSS to remove that:

body { margin: 0; padding: 0; }

If you're not loading HTML into your web view, but just the direct URL for an image file, I suggest either a) wrapping that in some basic HTML (head, body, an img tag), or b) downloading the image yourself (say with NSURLConnection), and displaying it directly in a UIImageView.

查看更多
我想做一个坏孩纸
4楼-- · 2020-02-04 07:50

As an ammendment to @thenextmillionair's brilliant answer, put the code in:

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    NSString *padding = @"document.body.style.margin='0';document.body.style.padding = '0'";
    [webView stringByEvaluatingJavaScriptFromString:padding];
}

as opposed to webViewDidFinishLoad. When the code is in webViewDidFinishLoad, you see the UIWebView reposition itself after appearing on screen with the padding. By putting it in webViewDidStartLoad, you eliminate this ugliness.

查看更多
登录 后发表回答