WKWebView ScaleToFit

Moving from UIWebView to WKWebView, I can't figure out how to make the HTML that I load using the loadHTMLString function in the size of WKWebView to fit the viewing restrictions. Now I get html to download, but it goes to the right and bottom of my view. How to scale it to fit my limitations?

+2
ios iphone ios9 wkwebview
Feb 23 '16 at 4:30
source share
3 answers

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

@IBOutlet var container: UIView! 

then import WebKit and initialize it, and then add as a subview of the container. To save a border, you must set it to a constraint value according to its parent representation. Here is how I did 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're done.

+6
Dec 18 '16 at 4:50
source share

This can mimic the scalePageToFit property of the UIWebView . stack overflow

0
Feb 26 '16 at 17:53 on
source share

An easy way to use WKWebView to fit your screen is to use the following code:

 var screenWidth: CGFloat { return UIScreen.main.bounds.size.width } var screenHeight: CGFloat { return UIScreen.main.bounds.size.height } yourWebView = WKWebView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight), configuration: WKWebViewConfiguration()) yourWebView.navigationDelegate = self yourContainerView.addSubview(yourWebView) 

stack overflow

-2
Feb 04 '19 at 12:34
source share



All Articles