Last active
May 29, 2024 19:57
-
-
Save christianselig/702c1759626db20aa905d740fe70e9c5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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