Zac
Zac

Reputation: 841

Is there a way to get keyboard input inside an NSMenuItem?

I'm trying to make an NSMenu which contains an NSMenuItem, and inside that NSMenuItem I want a TextField that I can interact with. My goal is to make a menubar note taking app, so in theory I could just make a window and align it with the top edge, but I want to use an NSMenu if possible for the aesthetic.

Problem is, the text field doesn't seem to be receiving input properly. The text cursor doesn't appear when I click on it, and no characters appear when I type. Also, as soon as I press a key, the menu disappears.

Here's my applicationDidFinishLaunching, which creates the menu itself and assigns it to a status bar item:

func applicationDidFinishLaunching(_ notification: Notification) {
    let contentView = ContentView()
    
    let view = NSHostingView(rootView: contentView)
    view.frame = NSRect(x: 0, y: 0, width: 350, height: 100)
    
    let item = NSMenuItem()
    item.view = view
    
    let menu = NSMenu()
    menu.addItem(item)
    
    self.statusBarItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
    self.statusBarItem.menu = menu
    self.statusBarItem?.button?.title = "Test"
}

And, here's my content view:

struct ContentView: View {
    var body: some View {
        TextField("Placeholder", text: ...some swiftUI thing...)
        .padding(10)
    }
}

Is there any way to do what I want, or will I have to resort to making a regular window and pretending it's an NSMenu?

Upvotes: 1

Views: 166

Answers (0)

Related Questions