我正在尝试根据其内容自动拥有一个UIWebView大小,虽然这很容易拉出正在加载的内容给我带来一些麻烦
我已经制作了一个简单的应用来测试这种行为,代码如下。
func webViewDidFinishLoad(_ webView: UIWebView)
{
print(webView.scrollView.contentSize.height)
webViewHeight.constant = webView.scrollView.contentSize.height
self.view.setNeedsUpdateConstraints()
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
}
override func viewDidLoad() {
super.viewDidLoad()
webView.loadHTMLString(htmlstring, baseURL: nil)
webView.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}
htmlstring如下
<blockquote class=\"instagram-media\" data-instgrm-captioned data-instgrm-version=\"7\" style=\" background:#FFF; border:0; border-radius:3px; box-shadow:0 0 1px 0 rgba(0,0,0,0.5),0 1px 10px 0 rgba(0,0,0,0.15); margin: 1px; max-width:658px; padding:0; width:99.375%; width:-webkit-calc(100% - 2px); width:calc(100% - 2px);\"><div style=\"padding:8px;\"> <div style=\" background:#F8F8F8; line-height:0; margin-top:40px; padding:50.0% 0; text-align:center; width:100%;\"> <div style=\"background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACwAAAAsCAMAAAApWqozAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAMUExURczMzPf399fX1+bm5mzY9AMAAADiSURBVDjLvZXbEsMgCES5/P8/t9FuRVCRmU73JWlzosgSIIZURCjo/ad+EQJJB4Hv8BFt+IDpQoCx1wjOSBFhh2XssxEIYn3ulI/6MNReE07UIWJEv8UEOWDS88LY97kqyTliJKKtuYBbruAyVh5wOHiXmpi5we58Ek028czwyuQdLKPG1Bkb4NnM+VeAnfHqn1k4+GPT6uGQcvu2h2OVuIf/gWUFyy8OWEpdyZSa3aVCqpVoVvzZZ2VTnn2wU8qzVjDDetO90GSy9mVLqtgYSy231MxrY6I2gGqjrTY0L8fxCxfCBbhWrsYYAAAAAElFTkSuQmCC); display:block; height:44px; margin:0 auto -44px; position:relative; top:-22px; width:44px;\"></div></div> <p style=\" margin:8px 0 0 0; padding:0 4px;\"> <a href=https://www.instagram.com/p/BLpA4TKAdPr/ style= \" color:#000; font-family:Arial,sans-serif; font-size:14px; font-style:normal; font-weight:normal; line-height:17px; text-decoration:none; word-wrap:break-word;\" target=\"_blank\"></p></div></blockquote> <script async defer src=\"http://platform.instagram.com/en_US/embeds.js\"></script>
(这是一个Instagram嵌入)
现在的问题是,如果你尝试运行这个webViewDidFinishLoad将被多次触发,这当然是预期的,但即使它完成了它的事情后,结果高度仍然不正确,因为嵌入将显示为切断
我认为这是因为后来通过AJAX或类似的东西加载图片,这意味着此时高度不考虑图片(甚至可能不是标题?)
我的问题是这个特定类型的内容,我无法更改,如何判断进程何时真正结束并获得WebView的正确大小?
答案 0 :(得分:0)
我们在Brave.app中观看了scrollview内容大小的变化:
webView.scrollView.addObserver(self, forKeyPath: "contentSize", options: .New, context: nil)
和接收者:
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "contentSize" {
// should give you correct height
print(webview.scrollView?.contentSize.height)
}
}
以下是此代码在我们的应用中的位置: https://github.com/brave/browser-ios/blob/d9b5500de863625fc4e7f1ade8f6c428842f3063/brave/src/frontend/BraveScrollController.swift#L195