WKWebView 在 Xcode 9 & Swift 4.0 中切断了我的其他视图

WKWebView is cutting off my other view in Xcode 9 & Swift 4.0

我刚开始使用 Xcode 和 Swift。

我 运行 在使用新的 WKWebView 时遇到了问题。我通常使用情节提要,但我了解到 Xcode 9 存在一个错误,如果您进行的构建包含 ios 11 之前的任何内容,则不允许您使用 WKWebView。我已经学会了但是,如果您以编程方式添加它并且一直按照 Apple 的说明进行操作,则这是可能的:https://developer.apple.com/documentation/webkit/wkwebview

我需要能够添加 Webview,同时允许 space 在我创建的用作横幅的自定义视图的顶部。此顶视图的高度为 116,在添加 Web 视图之前,约束适用于所有设备和方向。

当我添加 Webview 并添加它的自定义大小和约束时,webview 在所有设备和方向上也能完美运行。但是,我的顶部横幅视图丢失了。

我不确定我遗漏了什么,或者我是否为 Webview 编写了错误的代码。我会将屏幕截图和代码附加到 Webview。

非常感谢您的帮助!

This is the Webview tab that is missing the banner

This is another tab that shows what the banner looks like

import UIKit
import WebKit

class FirstViewController: UIViewController, WKUIDelegate {


var myWebView: WKWebView!

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

}
override func viewDidLoad() {
    super.viewDidLoad()

    myWebView = WKWebView(frame: CGRect( x: 0, y: 116, width: 414, height: 571), configuration: WKWebViewConfiguration() )
    self.view.addSubview(myWebView)
    myWebView.translatesAutoresizingMaskIntoConstraints = false

    myWebView.topAnchor.constraint(equalTo: view.topAnchor, constant: 116).isActive = true
    myWebView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 49).isActive = true
    myWebView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
    myWebView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
    myWebView.widthAnchor.constraint(equalToConstant: 414).isActive = true
    myWebView.heightAnchor.constraint(equalToConstant: 571).isActive = true


    let myURL = URL(string: "https://apple.com")
    let myRequest = URLRequest(url: myURL!)
    myWebView.load(myRequest)
}

移除宽度和高度限制,只要您正在设置 Leading 、 Trailing 、 Top 和 Bottom 限制,底部也应该 -49 而不是 49 as webViewBottom = mainviewBottom - 49

  myWebView.topAnchor.constraint(equalTo: view.topAnchor, constant: 116).isActive = true
  myWebView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -49).isActive = true
  myWebView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
  myWebView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true

您的横幅消失只是因为您在 loadView 方法的最后一行将 WKWebView 实例放入 ViewController 的 view 属性 中。尝试将其添加为子视图,甚至在 Interface Builder 中创建 2 个视图,第一个用于横幅,第二个用于 Web 视图,您还可以通过 IB 设置约束。