Created
May 29, 2024 19:58
-
-
Save christianselig/db67348f4001117958d145444941e296 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 containerView = UIView() | |
let webView = viewModel.createWebView() | |
webView.translatesAutoresizingMaskIntoConstraints = false | |
webView.load(URLRequest(url: URL(string: "https://apple.com")!)) | |
containerView.addSubview(webView) | |
NSLayoutConstraint.activate([ | |
webView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), | |
webView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), | |
webView.topAnchor.constraint(equalTo: containerView.topAnchor), | |
webView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor), | |
]) | |
return containerView | |
} | |
func updateUIView(_ uiView: UIViewType, context: Context) {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment