WebView的高度适合内容

时间:2018-06-28 17:43:34

标签: ios swift xcode webview

我尝试使Web视图适合其内容 我在跟随本教程:https://www.pixeldock.com/blog/set-a-uiwebviews-height-to-the-height-of-its-html-content-using-auto-layout/

但是deinit{ }从未被调用,我不明白为什么... 我尝试在功能stopObservingHeight()中设置didFinishNavigation,但是这是一个不好的主意,网络视图高度太短了

这是我的代码:

import UIKit
import WebKit

var MyObservationContext = 0

class ArticleViewController: ViewController {

@IBOutlet weak var articleWebView: WKWebView!

var observing = false
@IBOutlet weak var containerHeight: NSLayoutConstraint!

override func viewDidLoad() {
    super.viewDidLoad()

    articleWebView.navigationDelegate = self
    articleWebView.uiDelegate = self

    articleWebView.loadHTMLString(contentWebView, baseURL: nil)

    // Do any additional setup after loading the view.
}

deinit {
    stopObservingHeight()
}

func startObservingHeight() {
    let options = NSKeyValueObservingOptions([.new])
    articleWebView.scrollView.addObserver(self, forKeyPath: "contentSize", options: options, context: &MyObservationContext)
    observing = true;
}

func stopObservingHeight() {
    if observing {
        articleWebView.scrollView.removeObserver(self, forKeyPath: "contentSize", context: &MyObservationContext)
        observing = false
    }
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    guard let keyPath = keyPath,
        let context = context else {
            super.observeValue(forKeyPath: nil, of: object, change: change, context: nil)
            return
    }
    guard let change = change else { return }
    switch (keyPath, context) {
    case("contentSize", &MyObservationContext):
        containerHeight.constant = articleWebView.scrollView.contentSize.height
        print(articleWebView.scrollView.contentSize.height)
    default:
        super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
    }

}
}

extension ArticleViewController : WKUIDelegate, WKNavigationDelegate {

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print(articleWebView.scrollView.contentSize.height)
    containerHeight.constant = articleWebView.scrollView.contentSize.height
    if (!observing) {
        startObservingHeight()
    }
}
}

0 个答案:

没有答案