【问题标题】:uiwebview height calculation in swiftswift中的uiwebview高度计算
【发布时间】:2017-06-18 04:04:39
【问题描述】:

我有一个滚动视图,想动态添加多个 web 视图。需要获取 webview 的高度。我用过下面的代码。但它并不总是有效。有时显示错误的高度。 func webViewDidFinishLoad(aWebView: UIWebView) {

    let screenSize      = UIScreen.mainScreen().bounds
    let screenWidth     = screenSize.width
    var frame           = aWebView.frame
    frame.size.height   = 1
    frame.size.width    = screenSize.width
    aWebView.frame      = frame
    let fittingSize     = aWebView.sizeThatFits(CGSizeZero)
    frame.size          = fittingSize
    aWebView.frame      = frame

}

【问题讨论】:

    标签: uiwebview runtime height


    【解决方案1】:

    这是一个非常好的问题,将 Web 视图与其内容相匹配有一些有趣的应用,例如使用适合其内容的 Web 视图在地图上显示信息窗口。

    这是一个使用WKWebView 的解决方案,它首先创建一个 1×1px 大小的 Web 视图,加载其内容,并在相应地更新 Web 视图框架大小之前查询 Web 视图以找到其内容大小。有点hacky,但似乎是唯一的方法。

    import WebKit
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
            view.addSubview(webView)
            webView.navigationDelegate = self
            let htmlFile = Bundle.main.path(forResource: "index", ofType: "html")
            let html = try! String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
            webView.loadHTMLString(html, baseURL: nil)
        }
    }
    
    extension ViewController: WKNavigationDelegate {
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            var frame = webView.frame
            webView.evaluateJavaScript("document.documentElement.offsetWidth", completionHandler: { ret, _ in
                guard let width = ret as? CGFloat else { return }
                print("setting width: ", width)
                frame.size.width = width
                webView.frame = frame
    
                webView.evaluateJavaScript("document.documentElement.offsetHeight", completionHandler: { ret, _ in
                    guard let height = ret as? CGFloat else { return }
                    print("setting height: ", height)
                    frame.size.height = height
                    webView.frame = frame
                })
            })
        }
    }
    

    我的示例 HTML 文件 (index.html):

    <html>
        <head>
            <meta name="viewport" content="width=150, initial-scale=1.0">
        <style>
            html, body { margin: 0; padding: 0 };
    
        </style>
        </head>
        <body>
            <div style="height:280px;width:150px;background-color:cyan;"></div>
        </body>
    </html>
    

    注意:如果可能,您应该尝试使用WKWebView 而不是UIWebViewUIWebView 解决方案可能是可能的,但当WKWebView 应该更好地满足您的需求时,我认为不值得花费时间和精力。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      • 2016-05-19
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2015-11-15
      • 2015-08-24
      相关资源
      最近更新 更多