Skip to content

Instantly share code, notes, and snippets.

@christianselig
Last active May 29, 2024 19:57
Show Gist options
  • Save christianselig/702c1759626db20aa905d740fe70e9c5 to your computer and use it in GitHub Desktop.
Save christianselig/702c1759626db20aa905d740fe70e9c5 to your computer and use it in GitHub Desktop.
import SwiftUI
import WebKit
@main
struct WebViewActingUpApp: App {
var body: some Scene {
WindowGroup(id: "Main") {
ContentView()
}
WindowGroup(id: "Secondary") {
BrowserView()
}
}
}
struct BrowserView: View {
@State var viewModel = ViewModel()
var body: some View {
WebView(viewModel: viewModel)
}
}
struct ContentView: View {
@Environment(\.openWindow) private var openWindow
@Environment(\.dismissWindow) private var dismissWindow
var body: some View {
VStack {
Button("Open") { openWindow(id: "Secondary") }
Button("Close") { dismissWindow(id: "Secondary") }
}
}
}
@Observable
class ViewModel {
var webView: WKWebView?
@discardableResult
func createWebView() -> WKWebView {
if let webView { return webView }
let webView = WKWebView()
self.webView = webView
return webView
}
}
struct WebView: UIViewRepresentable {
let viewModel: ViewModel
func makeUIView(context: Context) -> some UIView {
let webView = viewModel.createWebView()
webView.load(URLRequest(url: URL(string: "https://apple.com")!))
return webView
}
func updateUIView(_ uiView: UIViewType, context: Context) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment