1
votes

I have loaded HTML in webview.  I want to dynamically update font size(increase or decrease) of text loaded in web view Same as in Apple News Article app. But According to my design I need to stop web view scrolling and need to update it height according to text. So I need to get content size of article, but I am not getting it proper. Can anyone help?

3
What you have tried provide the code! BTW stackoverflow.com/questions/27850792/… and stackoverflow.com/questions/3936041/… might be helpful.iPatel

3 Answers

1
votes

When font change at that time change Webview height to 1 than get proper offsetHeight for Webview

webView1.frame.size.height = 1
let size : String = self.webView1.stringByEvaluatingJavaScript(from: "document.documentElement.offsetHeight")!
0
votes

add below lines of code into your webViewDidFinishLoad

        webView.layoutSubviews()
        webView.frame.size.height = 1
        webView.frame.size = webView.sizeThatFits(.zero)
        print("WebView Height : \(webView.scrollView.contentSize.height)")
        webViewHgtConst.constant = webView.scrollView.contentSize.height
        webView.scalesPageToFit = true
        webView.scrollView.isScrollEnabled = false
        webView.scrollView.maximumZoomScale = 1.0
        webView.scrollView.minimumZoomScale = 1.0

and don't forget to add UIWebViewDelegate and add YOUR_WEBVIEW.delegate = self to your viewDidLoad

Hope this will help you

0
votes

First stop its scrolling :

         webView.scrollView.isScrollEnabled = false
         webView.scrollView.showsVerticalScrollIndicator = false
         webView.scrollView.showsHorizontalScrollIndicator = false
         webView.scrollView.bounces = false
         webView.loadHTMLString(dataHtmlString, baseURL: nil)

Make outlet of webView height Constraint and give its value by calculating its height:

     webviewHeightConst.constant  = (dataHtmlString.htmlAttributedString()?.height(withConstrainedWidth: yourwidthcont))!

This Extension Calculates height

extension String {

func htmlAttributedString() -> NSAttributedString? {
    guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
    guard let html = try? NSMutableAttributedString(
        data: data,
        options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil) else { return nil }

    var found = false

    html.beginEditing()
    html.enumerateAttribute(NSFontAttributeName, in: NSMakeRange(0, html.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (value, range, stop) in
        if (value != nil) {
                            let oldFont = value as! UIFont
                           let newFont = oldFont.withSize(16)
            html.addAttribute(NSFontAttributeName, value: newFont, range: range)
            found = true
        }
    }

    if !found{
        // No font was found - do something else?
    }
    html.endEditing()

    return html
}
}