Huang
Huang

Reputation: 21

How to use SwiftUI in NSMenu?

I'm new to Swift and I am developing a menubar app.

I have a SwiftUI view with a bunch of Picker and Text views, and display data. The SwiftUI in menubar NSMenu is not clickable and greyed out.

struct MainView: View {
    var body: some View {
        Picker("Hour", selection: $selectedHours) {
            ForEach(0...4, id: \.self) { hour in
                Text("\(hour)")
            }
        }
        Picker("Min", selection: $selectedMinutes) {
            ForEach(0...60, id: \.self) { minute in
                Text("\(minute)")
            }
        }
        ...
    }
}

This is my code which add view to NSMenu:

class ApplicationMenu: NSObject {
    let menu = NSMenu()
    
    func createMenu() -> NSMenu {
        let topView = NSHostingController(rootView: MainView().frame(width: 1000,height: 500))
        topView.view.frame.size = CGSize(width: 1000, height: 510)

        let customMenuItem = NSMenuItem()
        customMenuItem.view = topView.view
        menu.addItem(customMenuItem)
        menu.addItem(NSMenuItem.separator())
    }
}

How can I make this SwiftUI code clickable in NSMenu?

Upvotes: 2

Views: 242

Answers (0)

Related Questions