UIWebView动态内容大小

时间:2015-01-08 22:36:46

标签: swift uiwebview

我一直在环顾四周,并没有能够看到任何快速相关的方法来做到这一点。我试图让我的UIWebViews高度变得动态。我有一个UIWebView使用loadHtmlString函数加载数据。事实是我从sqlite数据库加载数据,每次我加载不同长度的不同字符串,自然web视图获得不同的高度。
现在我需要知道如何使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上发现了类似的内容但不确定如何将其链接到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
}

8 个答案:

答案 0 :(得分:34)

此帖已更新为Swift 5&amp; 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
}

答案 1 :(得分:16)

这只对我有用

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

创建了一个插座

答案 2 :(得分:6)

这是我使用自定义UIWebViews的自定义类,它包含所有内容以获取正确的scrollview内容高度,设置UIWebView高度并创建自定义高度约束以使autolayout工作。它还加载了一些自定义的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()
    }

}

答案 3 :(得分:4)

我遇到了问题:

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
}

答案 4 :(得分:1)

好的,我弄明白我做错了所以现在我知道如何调用这个函数。首先,我应该在我的班级中调用UIWebViewDelegate。然后将我的var jobSkillView设置为(jobSkillView.delegate = self)。现在这是我犯了重大错误的地方。在我的代码中,我有一个if else语句,我正在抛出我的func webViewDidLoad。我应该把它放在那个语句之外,并进入实际的类来覆盖我的UIWebView框架。说到框架****不要忘记将你的框架高度设置为1.然后只有这个功能才能用于你的UIWebView。之后,你应该为你的UIWebView for Swift提供一个功能齐全的高度。

答案 5 :(得分:1)

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

func webViewDidFinishLoad(_ webView: UIWebView) {        

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

}

答案 6 :(得分:1)

你可以使用这个类来制作webview大小以适应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()
    }

}

答案 7 :(得分:0)

我在加载中使用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
    })
}

}