WKWebView ScaleToFit

WKWebView ScaleToFit

从 UIWebView 移动到 WKWebView,我不知道如何使用 WKWebView 上的 loadHTMLString 函数使我正在加载的 HTML 大小适合视图边界。我现在加载了 html,但它超出了我视图的右侧和底部。如何缩放它以适合我的视野范围?

首先,在 StoryBoard 中创建一个容器视图,您将在其中添加 WKWebView 作为 subview:

@IBOutlet var container: UIView!

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

        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)

添加所需的 url 就完成了。