WKWebView ScaleToFit [英] WKWebView ScaleToFit

查看:431
本文介绍了WKWebView ScaleToFit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从UIWebView转到WKWebView,我无法弄清楚如何使用WKWebView大小的loadHTMLString函数来加载我正在加载的HTML以适应视图边界。我现在得到加载的HTML,但它在我的视图的右侧和底部。如何缩放它以适合我的视图边界?

Moving from UIWebView to WKWebView, I can not figure out how to make the HTML that I am loading using the loadHTMLString function on WKWebView size to fit the view bounds. I now get the html to load but it goes off the right and bottom of my view. How do I scale it to fit my view bounds?

推荐答案

首先,在 StoryBoard <中获取容器视图/ strong>您要将WKWebView添加为子视图

@IBOutlet var container: UIView!

然后导入 WebKit 并初始化它,然后添加为子视图容器。为了保留边界,您必须根据其父视图为其赋予约束值。我就是这样做的:

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.

这篇关于WKWebView ScaleToFit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆