Swift中的Web View动态高度问题

时间:2019-07-19 07:42:42

标签: swift webview

我正在从来自api响应的URL加载Web视图中的数据。 我希望Web视图根据URL数据的内容大小来获得高度。但它不能正常工作。

This is how my screen looks when I set constraints

我为我的网络视图高度限制设置了出口,并通过javascript函数将高度传递给了高度。这是我的代码,如何加载url并使其动态化,

func loadWeb(webURL: String) {
    self.activityIndicator = UIActivityIndicatorView()
    self.activityIndicator.center = self.headerView.center
    self.activityIndicator.style = UIActivityIndicatorView.Style.whiteLarge
    self.headerView.addSubview(self.activityIndicator)
    self.showActivityIndicator(show: true)

    let url = URL(string: webURL)
    self.webView.load(URLRequest(url: url!))
}

func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
    print(error.localizedDescription)
    self.showActivityIndicator(show: false)
    self.activityIndicator.isHidden = true
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    webView.frame.size.height = 1
    webView.frame.size = webView.scrollView.contentSize
    webView.frame.size = webView.sizeThatFits(.zero)
    webView.scrollView.isScrollEnabled = false

    self.webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
        if complete != nil {
            self.webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { (height, error) in
                self.webViewHeight.constant = height as! CGFloat
            })
        }
    })
}

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    print("Start to load")
    showActivityIndicator(show: true)
    self.view.isUserInteractionEnabled = false
    self.timer = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(self.hideIndicator), userInfo: nil, repeats: true)
}

func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
    DispatchQueue.main.async {
        print("finish to load")
        self.showActivityIndicator(show: false)
        self.activityIndicator.isHidden = true
    }
}

由于WebView中的URL加载,它没有达到理想的高度。如何获得。

0 个答案:

没有答案