WKWebView从一开始就没有显示在NSViewRepresentable中

时间:2019-10-21 18:00:50

标签: macos swiftui appkit

WKWebView放入View时遇到问题。如您所见,网页从一开始就没有显示。

enter image description here

当我更改应用程序窗口大小时,页面会正确显示。

enter image description here

可能是什么问题?

import SwiftUI
import WebKit

struct WebView: NSViewRepresentable {
    func makeNSView(context: Context) -> WKWebView  {
        let view = WKWebView()
        guard let url = URL(string: "https://github.com/filimo/ReaderTranslator") else { return view }
        view.load(URLRequest(url: url))
        return view
    }

    func updateNSView(_ view: WKWebView, context: Context) {

    }
}

struct WKWebViewDemo: View {
    var body: some View {
        WebView()
    }
}

如果我添加多行文本,则WKWebView的文本会更多。

struct WKWebViewDemo: View {
    var body: some View {
        VStack {
            Text("line\nline\nline\nline\nline\nline\nline\nline\nline\nline\nline\nline\n")
            WebView()
        }
    }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以找到我的解决方案here

import SwiftUI

struct WebViewContainer<Content>: View where Content: View {
    private let content: () -> Content

    init(@ViewBuilder content: @escaping () -> Content) {
        self.content = content
    }

    var body: some View {
        GeometryReader { geometry in
            ScrollView {
                self.content().frame(height: geometry.size.height)
            }
        }
    }
}

WebViewContainer {
    ViewRepresenter()
}