Iam working on MacOS Application, My entire code is written in Swift but for adding MenuItem I preferred to use SwiftUI ContentView. To do that I have written following code.
class StatusBarController {
var statusBar: NSStatusBar!
var statusItem: NSStatusItem!
var nsMenu = NSMenu()
init(delegate: AppDelegate) {
statusBar = NSStatusBar()
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
statusItem.button?.image = NSImage(systemSymbolName: "star.fill", accessibilityDescription: "Status bar icon")
let menuItem = NSMenuItem()
let controller = NSHostingController(rootView: ContentView())
controller.view.frame.size = CGSize(width: 250, height: 320)
menuItem.view = controller.view
nsMenu.addItem(menuItem)
statusItem.menu = nsMenu
}
}
This is working fine Im able to present ContentView successfully but in ContentView there is click action added on label. But it's taking multiple attempts(3-4) to just do single click. I did lot of research it seems issue of windows hierarchy. May be Contentview window is not in front and hence click is not passing through properly.What should I do here so that click will happen immediately in single click.
This is my content view:
struct ContentView: View {
var body: some View {
VStack(alignment: .leading, spacing: 0) {
HStack() {
Text("Quit")
.font(.title3)
.fontWeight(.medium)
.foregroundColor(.black)
.padding(.leading, 10)
.padding(.top, 10)
Spacer()
}
.contentShape(Rectangle()).onTapGesture {
//This is the action Im talking about
NSApp.terminate(self)
}
}
}
}