import AppKit
import SwiftUI
struct MyAlertView: View {
var body: some View {
VStack {
Text("This is a SwiftUI view in an alert.")
Button("OK") {
// Handle button action
}
}
.frame(width: 300, height: 200)
}
}
func activateApp() {
let myApp = NSRunningApplication.current
myApp.activate(options: .activateIgnoringOtherApps)
}
func showAlertWithSwiftUIView() {
let panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 300, height: 200),
styleMask: [.titled, .closable, .fullSizeContentView],
backing: .buffered,
defer: false)
panel.title = "Alert"
panel.center()
activateApp()
panel.makeKeyAndOrderFront(nil)
let hostingView = NSHostingView(rootView: MyAlertView(isPresented: .init(get: {
panel.isVisible
}, set: { isVisible in
if !isVisible {
panel.orderOut(nil)
}
})))
panel.contentView = hostingView
}