【问题标题】:How to add margin at top of WKWebView in IOS Swift如何在 IOS Swift 中的 WKWebView 顶部添加边距
【发布时间】:2019-11-08 02:47:39
【问题描述】:

我在 IOS swift 的 WKWebView 中显示了一个 pdf 文件,它显示得很好。我正在从服务器加载 pdf 文件。但是文件的某些部分隐藏在顶部导航栏后面。我想在 WKWebView 顶部添加边距。这是我当前的代码。

    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)

这里的注释代码是我尝试添加边距但不工作的方式。

【问题讨论】:

  • 尝试将这一行改成,webView = WKWebView(frame: self.view.frame - 64)
  • 设置WKWebView的框架参考这个link

标签: ios swift webview wkwebview


【解决方案1】:
webView = WKWebView(frame: self.view.frame)

在上面的行中设置框架,使其从顶部留出边距并从高度减少给定的边距。

【讨论】:

    【解决方案2】:

    尝试设置layoutMargin,应该可以解决问题。

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

    【讨论】:

      【解决方案3】:

      首先将webView 中的translatesAutoresizingMaskIntoConstraints 设置为false,即

          webView.translatesAutoresizingMaskIntoConstraints = false
      

      现在,将webView 的正确constraints 添加到view's safeAreaLayoutGuidelayoutMarginsGuide,即

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

      【讨论】:

        【解决方案4】:

        您可以使用以下行添加上边距

        webView = WKWebView(frame: CGRect(x: 0, y: 40, width: self.view.bounds.width, height: self.view.bounds.height - 40)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-01-20
          • 1970-01-01
          • 1970-01-01
          • 2016-05-27
          • 1970-01-01
          • 2016-10-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多