【问题标题】:Change webview height based on html text using autolayot in ios swift在ios swift中使用autolayot根据html文本更改webview高度
【发布时间】:2019-02-27 11:19:43
【问题描述】:

创建了一个加载 html 文本的 webview。

var html_string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."

self.webView.loadHTMLString(html_string, baseURL: nil)

我想将 webview 高度设置为其内容。无需在 webView 中滚动

【问题讨论】:

标签: ios swift xcode uiwebview wkwebview


【解决方案1】:

请注意组件是 WKWebView,Webview 已成为过去。

试试这个功能:

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 和 updateConstrain 创建一个 outlet。

你有一个美好的一天!

【讨论】:

    【解决方案2】:

    请使用以下代码,希望对您有所帮助。

    注意:- 'UIWebView' 在 iOS 12.0 中已弃用:不再支持,因此请使用 WKWebView 而不是 UIWebView

    对于 UIWebView

    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
    }
    

    对于 WKWebView

    如果你想使用 WKWebView 那么你需要做以下事情。

    1) 导入 WebKit

    2) 让你的 ViewController 继承自 WKNavigationDelegate

    3) 连接 WKWebView 的委托:webView.navigationDelegate = self

    4) 实现如下协议功能:

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

    【讨论】:

    • 感谢您的回复,但我没有得到完整的内容高度,我在故事板中提到了 webView 高度 200。如果内容高度超过 200,它不会增加高度而是提供可滚动视图
    • 嗨@nshivaprasadreddy 我认为你已经从情节提要中设置了固定高度200,你需要更新它,设置高度0或更高然后约束(高度> = 0)
    • 另一个选项不要仅通过自动调整大小来分配约束
    猜你喜欢
    • 2013-01-20
    • 1970-01-01
    • 2020-11-09
    • 2014-04-20
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    相关资源
    最近更新 更多