WKWebView全屏而不是框架?

时间:2017-10-18 09:45:15

标签: ios swift autolayout webkit wkwebview

我是Swift 3.0的新手,我需要一些帮助...

我正在尝试创建一个应该显示网站的框架。该网站不应该填写整个视图,而只是填充框架。每次我启动应用程序时,网站都会填满整个屏幕,而不仅仅是框架...... :(

这是我的代码:

import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate {


    @IBOutlet weak var webView: WKWebView!

    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        let myURL = URL(string: "https://www.google.com/")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }
}

我想要的是什么:

image

我得到了什么:

image

1 个答案:

答案 0 :(得分:3)

使用相等的填充为webview添加约束(锚点)。

尝试使用故事板布局:

从您的文件中删除loadView()代码:

enter image description here

或者以编程方式尝试:

import UIKit
import WebKit

class WebKitController: UIViewController {

    @IBOutlet weak var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let myURL = URL(string: "https://www.google.com/")
        let myRequest = URLRequest(url: myURL!)
        setupWKWebViewConstraints()
        webView.load(myRequest)
    }

    // add constraints to your web view
    func setupWKWebViewConstraints() {

        let paddingConstant:CGFloat = 30.0

        webView.translatesAutoresizingMaskIntoConstraints = false

        webView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: paddingConstant).isActive = true
        webView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -paddingConstant).isActive = true
        webView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: paddingConstant).isActive = true
        webView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -paddingConstant).isActive = true
    }

}