3

I am showing a pdf file in WKWebView in IOS swift, and it showing fine. I am loading pdf file from server. But some part of file is being hidden behind top navigation bar. I want to add margin at top of WKWebView. Here is my current code.

    let myBlog = file
    let url = NSURL(string: myBlog)
    let request = NSURLRequest(url: url! as URL)

    // init and load request in webview.
    webView = WKWebView(frame: self.view.frame)
    webView.navigationDelegate = self
    webView.load(request as URLRequest)

    self.view.addSubview(webView)

    // webView.translatesAutoresizingMaskIntoConstraints = false
    // webView.addConstraints([NSLayoutConstraint(item: webView, attribute: .height, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 1, constant: 0)])

    self.view.addSubview(sv)       
    let pdfVC = UIViewController()
    pdfVC.view.addSubview(webView)
    pdfVC.title = "File"
    self.navigationController?.pushViewController(pdfVC, animated: true)

enter image description here

Here the commented code is how I am trying to add margin and not working.

Umair Jameel
  • 1,573
  • 3
  • 29
  • 54

4 Answers4

1
webView = WKWebView(frame: self.view.frame)

In the line above set frame such that it leaves margin from top and reduce the given margin from the height.

Aman
  • 241
  • 2
  • 10
1

Try setting layoutMargin, It should solve the issue.

self.webView.layoutMargins = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)

Vittal Pai
  • 3,317
  • 25
  • 36
0

First of all set translatesAutoresizingMaskIntoConstraints of webView to false, i.e.

    webView.translatesAutoresizingMaskIntoConstraints = false

Now, add proper constraints of webView to view's safeAreaLayoutGuide or layoutMarginsGuide, i.e

    var guide: UILayoutGuide
    if #available(iOS 11.0, *) {
        guide = self.view.safeAreaLayoutGuide
    } else {
        guide = self.view.layoutMarginsGuide
    }

    NSLayoutConstraint.activate([
        webView.leadingAnchor.constraint(equalTo: guide.leadingAnchor),
        webView.trailingAnchor.constraint(equalTo: guide.trailingAnchor),
        webView.topAnchor.constraint(equalTo: guide.bottomAnchor),
        webView.bottomAnchor.constraint(equalTo: guide.bottomAnchor)
        ])
PGDev
  • 23,751
  • 6
  • 34
  • 88
0

you can add top margin by using the following line

webView = WKWebView(frame: CGRect(x: 0, y: 40, width: self.view.bounds.width, height: self.view.bounds.height - 40)
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Anjali
  • 19
  • 3