SwiftUI WebKit WKWebView:如何支持多url
SwiftUI WebKit WKWebView: how to support multi url
我开发了一个网站,现在想开发 iOS 应用程序。
我的想法是:
通过菜单更改新 url
struct ContentView: View {
var body: some View {
Webview(url: "https://readmorejoy.com")
HStack {
Menu("Menu") {
Button("menu1", action: {
// Webview(url: "https://readmorejoy.com")
})
Button("menu2", action: {})
Button("menu3", action: {})
}
}
}
}
在这里
struct ContentView: View {
@State private var urlString = "https://readmorejoy.com" // << initial !!
var body: some View {
Webview(url: urlString) // << use !!
HStack {
Menu("Menu") {
Button("menu1", action: {
self.urlString = "https://readmorejoy.com" // << update !!
})
Button("menu2", action: {})
Button("menu3", action: {})
}
}
}
}
好吧好吧
这是我的更新代码
struct Webview: UIViewRepresentable {
var url: String
func makeUIView(context: Context) -> WKWebView {
guard let url = URL(string: self.url) else {
return WKWebView()
}
let request = URLRequest(url: url)
let wkWebview = WKWebView()
wkWebview.load(request)
return wkWebview
}
func updateUIView(_ uiView: Webview.UIViewType, context: UIViewRepresentableContext<Webview>) {
if let url = URL(string: self.url) {
let request = URLRequest(url: url)
uiView.load(request)
}
}
}
我开发了一个网站,现在想开发 iOS 应用程序。
我的想法是: 通过菜单更改新 url
struct ContentView: View {
var body: some View {
Webview(url: "https://readmorejoy.com")
HStack {
Menu("Menu") {
Button("menu1", action: {
// Webview(url: "https://readmorejoy.com")
})
Button("menu2", action: {})
Button("menu3", action: {})
}
}
}
}
在这里
struct ContentView: View {
@State private var urlString = "https://readmorejoy.com" // << initial !!
var body: some View {
Webview(url: urlString) // << use !!
HStack {
Menu("Menu") {
Button("menu1", action: {
self.urlString = "https://readmorejoy.com" // << update !!
})
Button("menu2", action: {})
Button("menu3", action: {})
}
}
}
}
好吧好吧 这是我的更新代码
struct Webview: UIViewRepresentable {
var url: String
func makeUIView(context: Context) -> WKWebView {
guard let url = URL(string: self.url) else {
return WKWebView()
}
let request = URLRequest(url: url)
let wkWebview = WKWebView()
wkWebview.load(request)
return wkWebview
}
func updateUIView(_ uiView: Webview.UIViewType, context: UIViewRepresentableContext<Webview>) {
if let url = URL(string: self.url) {
let request = URLRequest(url: url)
uiView.load(request)
}
}
}