Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange Margin in WKWebView

Tags:

ios

swift

I have a UIViewController with a few UIViews (built using Interface Builder) including one that I want to use as a WKWebView. I have been able to create the WKWebView and load it as a subview to one of these UIViews -- but when I load the URL I get this strange padding on the top and left. I had the same issue when I use the UIWebView but was able to solve it using

self.automaticallyAdjustsScrollViewInsets = false;

However this does not seem to help at all with the WKWebView that has been loaded dynamically.

I also get the same padding when loading a page from the web so I know its not in my local html.

Edit: I am beginning to wonder whether autolayout in the container UIView is causing this...

Here is the relevant code:

    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)
}

Here is what it looks like. The BG color of the UIView container is dark grey -- and you'll also note that the html seems to extend beyond the UIView even though I set the frame of the WebView to be the same as the UIView container:

enter image description here

like image 742
bkurzius Avatar asked Jan 25 '16 00:01

bkurzius


People also ask

How can I clear the contents of a UIWebView WKWebView?

To clear old contents of webview With UIWebView you would use UIWebViewDelegate 's - webViewDidFinishLoad: .

What is WKWebView in Swift?

A WKWebView object is a platform-native view that you use to incorporate web content seamlessly into your app's UI. A web view supports a full web-browsing experience, and presents HTML, CSS, and JavaScript content alongside your app's native views.

How do I refresh WKWebView?

The WKWebView already contains a scrollview. All you need to do is create the refresh control, assign a target function that will get called when a user initiates a refresh, and attach the refresh control to the scrollview.


1 Answers

This is because WKWebView preserves space for the navigation bar by using an appropriate contentInset. However, since your WKWebView is a subview, this adjustment is not necessary anymore.

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

It is important to do this after the viewDidLoad method. For example in didFinishedNavigation in the WKNavigationDelegate

like image 57
Pieter Meiresone Avatar answered Oct 20 '22 00:10

Pieter Meiresone