Search code examples
iosuiwebviewswift3

Resizing text in UIWebView - Swift 3


I having a problem, resizing text within a UIWebView, the html file is located within the bundle. I have managed to get a modified script to work within obj-c, however using swift 3 there is no change to the text size, although the optimal value changes correctly at each click of the button. Here is the code -

import UIKit

class ViewController: UIViewController {

@IBOutlet var resWebView: UIWebView!

@IBOutlet weak var increaseFont: UIBarButtonItem!

@IBOutlet weak var decreaseFont: UIBarButtonItem!


var defaults  = ["textFontSize":40]


@IBAction func fontButtonPressed(sender: UIBarButtonItem) {

    var textFontSize = defaults["textFontSize"]

    switch sender.tag
    {
    case 1 : //when decrease
        textFontSize  = textFontSize! - 10

    case 2 ://when increase
        textFontSize = textFontSize! + 50
    default:
        break
    }

    defaults["textFontSize"] = textFontSize

    print(textFontSize)

    var jsString = "document.getElementsByTagName('body')[0].style.fontSize='\(defaults["textFontSize"])px'"
    resWebView.stringByEvaluatingJavaScript(from: jsString)
}


override func viewDidLoad() {
    super.viewDidLoad()

    let resFilePath = Bundle.main.url(forResource: "ResilienceHandbook", withExtension: "html");

    let resRequest = URLRequest(url: resFilePath!);
    resWebView.loadRequest(resRequest);


    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

Any pointers gratefully received - Thank you


Solution

  • As this is a web view, you can wrap content with "font size" attribute,

            let content = "<html><body><p><font size=30>" + webContent + "</font></p></body></html>"
            webView.loadHTMLString(content, baseURL: nil)
    

    Here change the size accordingly