WKWebView正在切断Xcode 9& S中的其他视图。 Swift 4.0

时间:2018-02-09 19:24:36

标签: ios swift xcode webview wkwebview

我对使用Xcode和Swift非常陌生。

我遇到了处理新WKWebView的问题。我通常使用故事板,但我了解到Xcode 9存在一个错误,如果您在ios 11之前进行包含任何操作的构建,则不允许您使用WKWebView。我已经了解如果您添加它可能但是以编程方式并遵循Apple的说明:https://developer.apple.com/documentation/webkit/wkwebview

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

当我添加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)
}

2 个答案:

答案 0 :(得分:0)

删除宽度和高度限制,只要您设置前导,尾随,顶部和底部约束,底部应该是-49而不是49,因为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

答案 1 :(得分:0)

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