Wkwebview Equivalent for Uiwebview's Scalespagetofit

WKWebView ScaleToFit

First of all, take a container view in StoryBoard under which you are going to add the WKWebView as a subview:

@IBOutlet var container: UIView!

then import WebKit and initialize it and later add as the subview of the container. In order to preserve the bound you have to give it constraint value according to its parent view. This is how I have done it:

        let webView = WKWebView(frame: .zero)
container.addSubview(webView)

webView.translatesAutoresizingMaskIntoConstraints = false
let height = NSLayoutConstraint(item: webView, attribute: .height, relatedBy: .equal, toItem: container, attribute: .height, multiplier: 1, constant: 0)
let width = NSLayoutConstraint(item: webView, attribute: .width, relatedBy: .equal, toItem: container, attribute: .width, multiplier: 1, constant: 0)
let leftConstraint = NSLayoutConstraint(item: webView, attribute: .leftMargin, relatedBy: .equal, toItem: container, attribute: .leftMargin, multiplier: 1, constant: 0)
let rightConstraint = NSLayoutConstraint(item: webView, attribute: .rightMargin, relatedBy: .equal, toItem: container, attribute: .rightMargin, multiplier: 1, constant: 0)
let bottomContraint = NSLayoutConstraint(item: webView, attribute: .bottomMargin, relatedBy: .equal, toItem: container, attribute: .bottomMargin, multiplier: 1, constant: 0)
container.addConstraints([height, width, leftConstraint, rightConstraint, bottomContraint])

let myURL = URL(string: "")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)

add the desired url and you are done.

Equivalent to UIWebView's paginationMode on WKWebView

Found it -
I added this to my css file

body {
overflow: -webkit-paged-x !important;
direction: rtl !important;
}

Watch out about WKWebview ignoring parts of your css... in that case add this as a prefix to your Html string -

""

or via helper method in an WKWebview extension

open func loadHTMLStringForWKWebview(_ string: String, baseURL: URL?)
{
// without this line WKWebview may ignore part in your css file
let headerString = ""
loadHTMLString(headerString+string, baseURL: baseURL)
}

make sure you add the right baseURL - in my case it is -

Bundle.main.bundleURL


Related Topics



Leave a reply



Submit