I am building a MacOS application which shows a menubar icon with a popover. I am using SwiftUI and building for Monterey only. I would like to change some app settings and I enabled a button inside the popover. Now, then the user presses the button, this should open a standard window where the user can add/change settings. The window is designed using SwiftUI.
So in my code, I tried to do something similar to this
struct ContentView: View {
var body: some View {
Text("Hello, World!")
.frame(maxWidth: .infinity, maxHeight: .infinity)
Button(action: {openWindow()}) { Text("SETTINGS")}
Spacer()
}
}
func openWindow() {
let window = NSWindow()
let contentView = ContentView()
window.aspectRatio = NSSize(width: 400, height: 400)
window.contentViewController = NSHostingController(rootView: contentView)
window.makeKey()
}
but nothing happen. So I am wondering few things:
Like in a normal SwiftUI app add this in the body of the @main
struct:
Settings {
SettingsView()
}
In the view representing the popover create a button or some other UI element to open the settings window. In the action call this
NSApp.sendAction(Selector(("showPreferencesWindow:")), to: nil, from: nil)
NSApp.activate(ignoringOtherApps: true)
The framework will provide a new window to display the SettingsView
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.