简体   繁体   中英

iOS, Swift: How do I allow readers to use Navigation Bar Button Items to adjust body font size in a WKWebView?

在此处输入图片说明

Greetings. I'm trying to use two programmatically created Navigation Bar Button Items (the smaller and the larger "A"s in the image above) to allow readers to increase or decrease the size of the text displayed in the WKWebView in an app for iPhones and iPads.

In the view controller, I have the following import statements:

import UIKit

import WebKit

In viewDidLoad, I have the following for creating the two Navigation Bar Button icons:

    let button1 = UIBarButtonItem(image: UIImage(named: "A_16x16"), style: .plain, target: self, action:#selector(decreaseFontSize))

    let button2 = UIBarButtonItem(image: UIImage(named: "A_28x28"), style: .plain, target: self, action:#selector(increaseFontSize))

    self.navigationItem.rightBarButtonItems = [button2, button1]

I also have started the following functions:

    func decreaseFontSize(_ button:UIBarButtonItem!) {

    fontSize = (fontSize > 14) ? fontSize-6 : fontSize
    let fontSpecifier = "document.body.style.fontSize = '" + String(fontSize) + "px'"
    print("decrease font size button pressed")
    print(fontSpecifier)
    textWebView.evaluateJavaScript(fontSpecifier, completionHandler: nil)

}

func increaseFontSize(_ button:UIBarButtonItem!) {

    fontSize = (fontSize < 50) ? fontSize+6 : fontSize
    let fontSpecifier = "document.body.style.fontSize = '" + String(fontSize) + "px'"
    print("increase font size button pressed")
    print(fontSpecifier)
    //textWebView.evaluateJavaScript("document.body.style.fontSize = '40px'", completionHandler: nil)
    textWebView.evaluateJavaScript(fontSpecifier, completionHandler: nil)

}

The CSS for the HTML texts includes these styles:

  body {
      color: black;
      background: white;
      font-size: 1.2em; /*20px; but use em */
      text-align: left;
      font-family: "MyCustomFont", sans-serif;
      margin-right: 8px;
      margin-left: 8px;
  }

This works somewhat, but "MyCustomFont" (or MyCustomFont without quotes) is ignored. I so would love to have the custom font displayed.

Any guidance or proposed solutions would be appreciated.

Thanks to Aditya Deshmane's answer to Using custom fonts in WKWebView I put this at the top of my CSS file and my custom font is displayed:

    @font-face {
        font-family: 'MyCustomFont';
        src: local('MyCustomFont'),url('MyCustomFont.ttf') format('truetype');
    }

The icons seem to adjust the font size as desired in my iPad-mini 4 but "work" somewhat inconsistently in my iPhone 6. I'm not yet accepting this, my own answer, as "the accepted answer" as there is room for improvement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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