Umair Jameel
Umair Jameel

Reputation: 1673

How to add margin at top of WKWebView in IOS Swift

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.

Upvotes: 3

Views: 3759

Answers (4)

Anjali
Anjali

Reputation: 19

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)

Upvotes: 0

PGDev
PGDev

Reputation: 24341

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

Upvotes: 0

Vittal Pai
Vittal Pai

Reputation: 3553

Try setting layoutMargin, It should solve the issue.

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

Upvotes: 1

Aman
Aman

Reputation: 241

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.

Upvotes: 1

Related Questions