简体   繁体   English

在ios swift中使用autolayot根据html文本更改webview高度

[英]Change webview height based on html text using autolayot in ios swift

created a webview which loads html text.创建了一个加载 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)

i want set webview height to its content.without scrolling in the webView我想将 webview 高度设置为其 content.without 在 webView 中滚动

Mind that the component is WKWebView , Webview is a thing of the past.请注意,该组件是WKWebView ,Webview 已成为过去。

Try this function:试试这个功能:

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
}

Remember to create an outlet for myWebViewHeightConstraint and updateConstrain as well.请记住为 myWebViewHeightConstraint 和 updateConstrain 创建一个出口。

You have a nice day!你有美好的一天!

Use following code for this, I hope this helps you.为此使用以下代码,希望对您有所帮助。

Note:- 'UIWebView' was deprecated in iOS 12.0: No longer supported, So please use WKWebView instead of UIWebView注意:- 'UIWebView' 在 iOS 12.0 中被弃用:不再支持,所以请使用WKWebView而不是UIWebView

For 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
}

For WKWebView对于 WKWebView

If you want to use WKWebView then you need to do the following things.如果你想使用 WKWebView 那么你需要做以下事情。

1) import WebKit 1)导入WebKit

2) make your ViewController inherit from WKNavigationDelegate 2) 让你的 ViewController 继承自 WKNavigationDelegate

3) hook up the WKWebView's delegate: webView.navigationDelegate = self 3)连接WKWebView的delegate:webView.navigationDelegate = self

4) implement the following protocol function: 4)实现如下协议功能:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM