WKWebview Swift 4保持全面筛选Xcode 9

时间:2018-01-23 21:15:09

标签: ios swift xcode

我有一个带有Web视图的快速4项目我想将WKWebview保持这个大小:

https://i.stack.imgur.com/3mKVb.png

不幸的是,webview一直显示为全屏窗口,并且不符合大小。

这是我正在使用的代码: 导入UIKit 导入WebKit class ViewController:UIViewController,WKUIDelegate {

@IBOutlet 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.apple.com")
    let myRequest = URLRequest(url: myURL!)
    webView.load(myRequest)
}}

1 个答案:

答案 0 :(得分:0)

这是我用于编程WKWebView设置约束的代码:

override func viewDidLoad() {
    super.viewDidLoad()

    let webConfiguration = WKWebViewConfiguration()
    webConfiguration.websiteDataStore = WKWebsiteDataStore.default()
    let webView = WKWebView(frame: .zero, configuration: webConfiguration)

    webView.navigationDelegate = self
    webView.uiDelegate = self

    self.webView = webView

    if let webView = self.webView
    {
        view.addSubview(webView)
        webView.translatesAutoresizingMaskIntoConstraints = false
        let height = NSLayoutConstraint(item: webView, attribute: .height, relatedBy: .equal, toItem: self.contentView, attribute: .height, multiplier: 1, constant: 0)
        let width = NSLayoutConstraint(item: webView, attribute: .width, relatedBy: .equal, toItem: self.contentView, attribute: .width, multiplier: 1, constant: 0)
        let offset = NSLayoutConstraint(item: webView, attribute: .top, relatedBy: .equal, toItem: self.contentView, attribute: .top, multiplier: 1, constant: 0)
        view.addConstraints([height, width, offset])
    }
}

这与您正在进行的操作不同,因为它设置了自动布局限制。在这种情况下,我有一个名为contentView的视图,在我的故事板中是一个简单的UIView,它被固定在超级视图上:

enter image description here