我得到了以下swiftUI代码:
import SwiftUI
import WebKit
struct WebView: NSViewRepresentable {
func makeNSView(context: Context) -> WKWebView {
let view: WKWebView = WKWebView()
guard let url: URL = URL(string: "https://google.com") else { return view }
let request: URLRequest = URLRequest(url: url)
view.load(request)
return view
}
func updateNSView(_ view: WKWebView, context: Context) {
}
}
struct ContentView: View {
var body: some View {
WebView()
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
问题在于它只显示一个空视图。我该如何解决?
答案 0 :(得分:4)
您可以使用下面的代码,它使用NSViewRepresentable
struct WebView: NSViewRepresentable {
let view: WKWebView = WKWebView()
var request: URLRequest {
get{
let url: URL = URL(string: "https://google.com")!
let request: URLRequest = URLRequest(url: url)
return request
}
}
func makeNSView(context: Context) -> WKWebView {
view.load(request)
return view
}
func updateNSView(_ view: WKWebView, context: Context) {
view.load(request)
}
}
struct ContentView: View {
var body: some View {
GeometryReader { g in
ScrollView {
WebView()
.frame(height: g.size.height)
}.frame(height: g.size.height)
}
}
}
如果仍然无法加载,请转到功能并检查传入和传出的连接。