WKWebView中的奇怪边距

18

我有一个UIViewController,其中包含几个UIView(使用Interface Builder构建),其中包括一个我想用作WKWebView的视图。我已经能够创建WKWebView并将其加载为其中一个UIView的子视图,但是当我加载URL时,顶部和左侧会出现奇怪的填充。我在使用UIWebView时也遇到了同样的问题,但是通过使用 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 能够解决它。

self.automaticallyAdjustsScrollViewInsets = false;

然而,这似乎对动态加载的 WKWebView 没有任何帮助。

当从网络加载页面时,我也会遇到同样的填充,因此我知道这不是在我的本地 html 中。

编辑:我开始怀疑容器 UIView 中的自动布局是否导致了这个问题……

这是相关的代码:

    var webView:WKWebView!
@IBOutlet var containerView : UIView?
@IBOutlet weak var webContainer: UIView!

override func loadView() {
    super.loadView()
    self.webView = WKWebView()
    if(self.webView != nil){
        self.containerView = self.webView!
        self.containerView!.frame = self.webContainer.frame
        self.webContainer.addSubview(self.containerView!)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    let bundle = NSBundle.mainBundle()
    let url = bundle.URLForResource("index", withExtension: "html")
    let request = NSURLRequest(URL: url!)
    webView.loadRequest(request)
}

这就是它的外观。UIView容器的背景颜色是暗灰色 - 你也会注意到尽管我将WebView的框架设置为与UIView容器相同,但html似乎超出了UIView的范围:

在此输入图片描述


我在webview中自己加载HTML源代码。添加style标签并将margin设置为零对我有用。<style>body{margin:0;}</style> - akshay1188
3个回答

15

这是因为 WKWebView 通过使用适当的 contentInset 为导航栏保留空间。然而,由于您的 WKWebView 是子视图,因此不再需要进行此调整。

self.webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)

viewDidLoad方法之后做这件事情非常重要。例如,在WKNavigationDelegatedidFinishedNavigation中。


11
有趣的事实是,在Swift中,这样写起来甚至更可爱:webView.scrollView.contentInset = .zero - Kane Cheshire
2
Objective-C 的等效代码为:webView.scrollView.contentInset = UIEdgeInsetsZero - Son of a Beach

10
self.automaticallyAdjustsScrollViewInsets = NO;
  if (@available(iOS 11.0, *)) {
    self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  }

2
你好,你的答案可能是正确的,但请尝试添加一些代码解释 :) - Ali
1
错误的语言。 - matt
6
在Swift 5中,以下内容已足够: webView.scrollView.contentInsetAdjustmentBehavior = .never - Mike Marcacci
这个答案是正确的! - Alexey

0

应该使用WKNavigationDelegate

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
NSString *cssString = @"body { padding:0; margin:0}";
NSString *jsString = [NSString stringWithFormat:@"var style = document.createElement('style'); style.innerHTML = '%@'; document.head.appendChild(style);", cssString];
[webView evaluateJavaScript:jsString completionHandler:nil];}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接