UIWebView动态内容大小

UIWebView dynamic content size

我环顾四周,没能找到任何 swift 相关的方法来做到这一点。我试图让我的 UIWebViews 高度是动态的。我有一个使用 loadHtmlString 加载数据的 UIWebView function.The 事情是我从 sqlite 数据库加载数据,每次我加载不同长度的不同字符串时,网络视图自然会获得不同的高度。
现在我需要知道如何使 UIWebView 达到准确的高度,以便在 webView 下加载我的下一个内容。这是我目前所拥有的

var jobSkillView = UIWebView(frame: CGRectMake(-5, 480.0, screenWidth, 300.0))
jobSkillView.loadHTMLString("<html><body p style='font-family:arial;font-size:16px;'>" + jobSkills + "</body></html>", baseURL: nil)
jobSkillView.stringByEvaluatingJavaScriptFromString("document.body.innerHTML")
jobSkillView.scrollView.scrollEnabled = true
jobSkillView.scrollView.bounces = true
jobSkillView.sizeToFit()
border.addSubview(jobSkillView)

我在 SO 上找到了类似的东西,但不确定如何 link 它到 UIWebView 的框架:

func webViewDidFinishLoad(jobSkillView : UIWebView){
    // Change the height dynamically of the UIWebView to match the html content
    var jobSkillViewFrame: CGRect = jobSkillView.frame
    jobSkillViewFrame.size.height = 1
    jobSkillView.frame = jobSkillViewFrame
    var fittingSize: CGSize = (jobSkillView.sizeThatFits(CGSizeZero))
    jobSkillViewFrame.size = fittingSize
    // webViewFrame.size.width = 276; Making sure that the webView doesn't get wider than 276 px
    jobSkillView.frame = jobSkillViewFrame
    var jobSkillViewHeight = jobSkillView.frame.size.height
}

好的,我知道我做错了什么,所以现在我知道如何调用这个函数了。首先,我应该在 class 中调用 UIWebViewDelegate。然后将我的 var jobSkillView 设置为 (jobSkillView.delegate = self)。现在这是我犯下重大错误的地方。在我的代码中,我有一个 if else 语句,我正在将我的 func webViewDidLoad 放入其中。我应该将它从该语句中取出并放入实际的 class 中以覆盖我的 UIWebView 框架。说到 frame **** 不要忘记将 FRAME HEIGHT 设置为 1。只有这样,此功能才适用于您的 UIWebView。之后,您应该为 Swift.

的 UIWebView 提供一个完全基于功能的高度

这是我的自定义 class 用于自定义 UIWebView,它包含获取正确的滚动视图内容高度、设置 UIWebView 高度并创建自定义高度约束以使自动布局正常工作的所有内容。它还加载了一些自定义 CSS 样式...

class CustomUIWebView: UIWebView, UIWebViewDelegate {

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.scrollView.scrollEnabled = false
        self.scrollView.bounces = false
        self.delegate = self
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.scrollView.scrollEnabled = false
        self.scrollView.bounces = false
        self.delegate = self
    }

    override func loadHTMLString(string: String!, baseURL: NSURL!) {
        var cssURL:String = NSBundle.mainBundle().pathForResource("webview", ofType: "css")!
        var s:String = "<html><head><title></title><meta name=\"viewport\" content=\"initial-scale=1, user-scalable=no, width=device-width\" /><link rel=\"stylesheet\" href=\"./webview.css\" ></link></head><body>"+string+"</body></html>";
        var url:NSURL

        if baseURL == nil {
            url = NSBundle.mainBundle().bundleURL
        } else {
            url = baseURL
        }

        super.loadHTMLString(s, baseURL: url)
    }

    func webViewDidFinishLoad(webView: UIWebView) {
        self.webViewResizeToContent(webView)
    }

    func webViewResizeToContent(webView: UIWebView) {
        webView.layoutSubviews()

        // Set to smallest rect value
        var frame:CGRect = webView.frame
        frame.size.height = 1.0
        webView.frame = frame

        var height:CGFloat = webView.scrollView.contentSize.height
        println("UIWebView.height: \(height)")

        webView.setHeight(height: height)
        let heightConstraint = NSLayoutConstraint(item: webView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Height, multiplier: 1.0, constant: height)
        webView.addConstraint(heightConstraint)

        // Set layout flag
        webView.window?.setNeedsUpdateConstraints()
        webView.window?.setNeedsLayout()
    }

}

此 post 已更新 Swift 5 & WKWebView


所以这是你在那里写的一个非常棒的函数,OP!
这只是您的代码的一个更短、更优雅的版本:

// make sure to declare the delegate when creating your webView (add UIWebViewDelegate to class declaration as well)
myWebView.delegate = self

func webViewDidFinishLoad(webView: UIWebView) {
     webView.frame.size.height = 1
     webView.frame.size = webView.sizeThatFits(CGSize.zero)
}

迁移到 WKWebView

1) 导入 WebKit
2) 让你的 ViewController 继承自 WKNavigationDelegate
3) 连接 WKWebView 的代表:webView.navigationDelegate = self
4) 实现如下协议功能:

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

UIWebView 迁移到 WKWebView 后,上述方法似乎不再有效。
您可以做的是将带有 webView.sizeThatFits(CGSize.zero) 的行更改为:

webView.frame.size = webView.scrollView.contentSize

WKWebView 的完整代码将是:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.frame.size.height = 1
    webView.frame.size = webView.scrollView.contentSize
}

使用以下代码使您的 UIWebView 高度在 Swift 3.x

中动态变化
func webViewDidFinishLoad(_ webView: UIWebView) {        

 let height = webView.scrollView.contentSize.height
 var wRect = webView.frame
 wRect.size.height = height
 webView.frame = wRect

}

这只对我有用

func webViewDidFinishLoad(_ webView: UIWebView) {
    webView.frame.size.height = 1
    webView.frame.size = webView.sizeThatFits(.zero)
    webView.scrollView.isScrollEnabled=false;
    myWebViewHeightConstraint.constant = webView.scrollView.contentSize.height
    webView.scalesPageToFit = true
}

确保您已经为 myWebViewHeightConstraint 创建了一个 outlet

当时更改字体时,将 Webview 高度更改为 1,然后为 Webview

获得正确的 offsetHeight
webView1.frame.size.height = 1

您可以使用此 class 使网页视图大小适合 swift 3 和 swift 4

//
//  RSWebView.swift
//  CustumWebViewDemo
//
//  Created by Ruchin Somal on 01/01/18.
//  Copyright © 2018 Ruchin Somal. All rights reserved.
//

import UIKit

class RSWebView: UIWebView, UIWebViewDelegate {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        self.scrollView.isScrollEnabled = false
        self.scrollView.bounces = false
        self.delegate = self
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.scrollView.isScrollEnabled = false
        self.scrollView.bounces = false
        self.delegate = self
    }

    override func loadHTMLString(_ string: String?, baseURL: URL?) {
        let s:String = "<html><head><title></title><meta name=\"viewport\" content=\"initial-scale=1, user-scalable=no, width=device-width\" /><link rel=\"stylesheet\" href=\"./webview.css\" ></link></head><body>"+string!+"</body></html>";
        var url:URL

        if baseURL == nil {
            url = Bundle.main.bundleURL
        } else {
            url = baseURL!
        }

        super.loadHTMLString(s, baseURL: url)
    }

    func webViewDidFinishLoad(_ webView: UIWebView) {
        self.webViewResizeToContent(webView: webView)
    }

    func webViewResizeToContent(webView: UIWebView) {
        webView.layoutSubviews()

        // Set to initial value of webview
        var frame:CGRect = webView.frame
        frame.size.height = 1.0
        webView.frame = frame

        // Calculated height of webview
        let wvheight: CGFloat = webView.scrollView.contentSize.height
        print("UIWebView.height: \(wvheight)")
        var wvRect = webView.frame
        wvRect.size.height = wvheight
        webView.frame = wvRect

        let heightConstraint = NSLayoutConstraint(item: webView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.height, multiplier: 1.0, constant: wvheight)
        webView.addConstraint(heightConstraint)

        webView.window?.setNeedsUpdateConstraints()
        webView.window?.setNeedsLayout()
    }

}

我遇到了问题:

let height = webView.scrollView.contentSize.height

有时我的网络视图高度根本没有计算并保持默认值。 所以最后我设法找到更好的解决方案,只需将该行代码替换为:

let height = webView.stringByEvaluatingJavaScript(from: "document.body.scrollHeight")

这是我的最终完整代码:

    func webViewDidFinishLoad(_ webView: UIWebView) {

    //webview height
    webView.frame.size.height = 1
    webView.frame.size = webView.sizeThatFits(.zero)
    webView.scrollView.isScrollEnabled = false
    let height = webView.stringByEvaluatingJavaScript(from: "document.body.scrollHeight")
    if let height = height {
        if let heightInt = Int(height) {
            let heightFloat = Float(heightInt)

            webViewHeightConstraint.constant = CGFloat(heightFloat)
        }
    }
    webView.scalesPageToFit = true
}

我在我的负载中使用 HTML 字符串并且必须在 Webview 委托中使用以下方法:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.evaluateJavaScript("document.documentElement.scrollHeight", completionHandler: { (height, error) in
        self.webviewHeightConstraint?.constant = height as! CGFloat
    })
}

和完整代码:

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

@IBOutlet weak var webviewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var webview: WKWebView!
var observing = false

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    webview.navigationDelegate = self
    webview.scrollView.isScrollEnabled = false

        self.webview.loadHTMLString("""
        <html>
        <head>
        <style>
        ul {
        list-style: none;
        }

        ul li::before {
        content: "\2022";
        color: red;
        font-weight: bold;
        display: inline-block;
        width: 1em;
        margin-left: -1em;
        }
        </style>
        </head>
        <body>

        <h2>Change Bullet Color of List Items</h2>

        <ul>
        <li>Adele</li>
        <li>Agnes</li>
        <li>Billy</li>
        <li>Bob</li>
        <li>Bob</li>
        <li>Bob</li>
        <li>Bob</li>
        <li>Bob</li>
        <li>Bob</li>
        <li>Bob</li>
        <li>Bob</li>
        <li>Bob</li>
        <li>Bob</li>
        <li>Bob</li>
        </ul>

        </body>
        </html>
""", baseURL: nil)
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.evaluateJavaScript("document.documentElement.scrollHeight", completionHandler: { (height, error) in
        self.webviewHeightConstraint?.constant = height as! CGFloat
    })
}

}

试试

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.frame.size.height = 1
        webView.frame.size = webView.sizeThatFits(.zero)
        webView.scrollView.isScrollEnabled = false
        let height = webView.scrollView.contentSize.height
}