【问题标题】:Cocoa Swift: WKWebView is not showing when is add it as subviewCocoa Swift:WKWebView 未显示何时将其添加为子视图
【发布时间】:2019-04-11 23:02:29
【问题描述】:

我正在尝试将 WKWebView 添加为子视图:

func loadWebView() {

    let userAgentStr = self.getUserAgent()
    if let url = URL(string: videoURL.stringValue){
        let request  = URLRequest.init(url: url)
        let config = WKWebViewConfiguration()
        self.webView = WKWebView(frame: self.view.frame, configuration: config)
        self.webView.wantsLayer = true
        self.webView.customUserAgent = userAgentStr
        self.webView.load(request)
        self.webView.layer?.backgroundColor = NSColor.green.cgColor
        self.view.addSubview(self.webView)
        self.view.needsDisplay = true

    }
}

但没有显示在主 NSView 中。但被添加为子视图:

po self.view.subviews
▿ 9 elements
  - 0 : <NSTextField: 0x10050e400>
  - 1 : <NSTextField: 0x10050f7f0>
  - 2 : <NSTextField: 0x10050e8e0>
  - 3 : <NSButton: 0x600003510000>
  - 4 : <NSButton: 0x6000035100b0>
  - 5 : <NSTextField: 0x10050ee00>
  - 6 : <NSButton: 0x600003510160>
  - 7 : <NSView: 0x6000033054a0>
  - 8 : <WKWebView: 0x600003e01400>

我试图看看我是否做错了什么并将其添加为 NSView 作为子视图:

func loadNSView() {
    let newView = NSView()
    newView.frame = self.view.frame
    newView.wantsLayer = true
    newView.layer?.backgroundColor = NSColor.white.cgColor
    self.view.addSubview(newView)
    self.view.needsDisplay = true
}

它工作得很好。

你们中的任何人都知道我做错了什么吗?或者我该怎么做才能加载 WKWebView ?

非常感谢您的帮助。

【问题讨论】:

  • 这可能无关紧要,但说self.webView = WKWebView(frame: self.view.frame) 几乎是不对的。你的意思是self.webView = WKWebView(frame: self.view.bounds)
  • @matt 我试过self.webView = WKWebView(frame: self.view.bounds, configuration: config) 但没有成功
  • 不,我说这可能无关紧要。 :) 但是,养成正确的习惯仍然很重要。 — 让我们来解决您的实际问题。你能做实验吗?如果你说delay(2) {self.webView.load(request)},而不是self.webView.load(request),它会让事情变得更好吗? (我的delay 函数是here。)我问是因为如果是这样,它表明在请求真正进入界面之前尝试将请求加载到 Web 视图中可能是问题所在。
  • @matt,没有变化。仍然没有显示 webView。

标签: swift cocoa wkwebview nsview xcode10.2


【解决方案1】:

我找到了这个问题的根源。由于是 MacOS (Cocoa) 应用程序,您需要启用传入和传出连接:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多