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

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?

Related

Request key for TextField in macOS status bar app

I am writing a little status bar app, which includes a text input.
The app is added to the status bar as a NSMenuItem which holds a NSHostingViewController with the SwiftUI-View. The status bar menu is added through an App delegate inside SwiftUIs #main scene. I've set "Application is agent" in the info.plist to true and I have an empty scene as #main in SwiftUI.
Problem: When I try to edit text, in the status bar app, the text field is not clickable and does not receive text input. When I add a window, the text field in the status bar app works as expected as long as the window is in foreground.
From my understanding, this is caused by the text field not being inside a window marked as key window. Is there any workaround to make the text field work as expected without the need for an additional app window?
Minimal example for the app delegate:
class AppDelegate: NSObject, NSApplicationDelegate {
private var statusItem: NSStatusItem?
func applicationDidFinishLaunching(_ notification: Notification) {
self.statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
if let statusBarButton = statusItem?.button {
statusBarButton.image = NSImage(systemSymbolName: "6.circle", accessibilityDescription: "")
statusBarButton.image?.isTemplate = true
}
let menuItem = NSMenuItem()
menuItem.view = createView()
let menu = NSMenu()
menu.addItem(menuItem)
statusItem?.menu = menu
}
private func createView() -> NSView {
let view = HostingView(rootView: ContentView())
view.frame = NSRect(x: 0, y: 0, width: 520, height: 260)
return view
}
}
SwiftUI #main
import SwiftUI
import AppKit
#main
struct MacApp: App {
#NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
Settings {
EmptyView()
}
}
}
Edit: I figured out, that there are two windows registered for my app. One for the status bar icon and one for the menu. However, the code below does not result in the menu window to become the key window. (although it is in fact the only window which returns true for .canBecomeKey)
.onAppear {
let window = NSApp.windows.first { $0.canBecomeKey }
window?.makeKey()
}
Second Edit: Apparently, the problem is not, that the window is not able to become key, but that the app is not set as the active app when the status bar menu is opened. I came up with this rather ugly hack, which causes the menu to close and re-open when another app was in focus before, but at least buttons and textfields work as expected with this:
func applicationDidFinishLaunching(_ notification: Notification) {
...
// Also let AppDelegate implement NSMenuDelegate
menu.delegate = self
...
}
func menuWillOpen(_ menu: NSMenu) {
#warning("This is a hack to activate the app when the menu is shown. This will cause the menu to close and re-open when another window was focused before.")
if !NSApp.isActive {
NSApp.activate(ignoringOtherApps: true)
DispatchQueue.main.async {
self.statusItem?.button?.performClick(nil)
}
}
}
I am still looking for a proper solution.

My NSWindow's shadow is getting cut off when switching screens?

I wanted to have an NSWindow with a blurred background so I created a wrapper for NSVisualEffectView to be used in my ContentView() with some help from How do you blur the background in a SwiftUI macOS application?. I also tried doing it with just the NSWindow using https://github.com/lukakerr/NSWindowStyles#:~:text=true-,6.%20Vibrant%20background,A,-vibrant.
struct VisualEffectView: NSViewRepresentable
{
let material: NSVisualEffectView.Material
let blendingMode: NSVisualEffectView.BlendingMode
func makeNSView(context: Context) -> NSVisualEffectView
{
let visualEffectView = NSVisualEffectView()
visualEffectView.material = material
visualEffectView.blendingMode = blendingMode
visualEffectView.state = NSVisualEffectView.State.active
return visualEffectView
}
func updateNSView(_ visualEffectView: NSVisualEffectView, context: Context)
{
visualEffectView.material = material
visualEffectView.blendingMode = blendingMode
}
}
It works and looks great, however, when I move the window to a different screen -and pause with the window between both screens, then move it to the next window- it chops off a part of the NSWindow's shadow.
This is what it looks like when moving screens ⤵︎
Is there a way to prevent this shadow chop from happening?
Interface: SwiftUI
LifeCycle: Appkit AppDelegate
Figured it out! Without any hacks too thankfully lol
Rules
In order to achieve this look without the nasty artifacts in the question you have to do a few things the way macOS wants them.
1. Don't set your NSWindow.backgroundColor = .clear!
This is the cause for the nasty artifacts above in the first place! Leaving your window's color as is will make sure the window functions properly when changing screens. NSVisualEffectView captures the image behind the window and uses that for the background so there's no need to make anything transparent.
2. Make sure to include .titled in the window's styleMask!
Failure to do so will render the window without rounded corners. If you attempt to add rounded corners (like I did) to the SwiftUI view you will still have an opaque background on the NSWindow itself. If you then set your window's background color to .clear (like I did again) the shadow chop issues will ensue! However, this does not mean that the title bar will get in the way, it won't, we'll get to that in a bit.
3. Add your NSVisualEffectView to your SwiftUI view!
I found this to be easier than adding the visual effect to the NSWindow.contentView as a subview.
Solution
1. So start off by setting up your NSWindow and AppDelegate! ⤵︎
All you're doing is making sure the titlebar is present but hidden.
import Cocoa
import SwiftUI
#main
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Create the window and set the content view.
// Note: You can add any styleMasks you want, just don't remove the ones below.
window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 300, height: 200),
styleMask: [.titled, .fullSizeContentView],
backing: .buffered, defer: false)
// Hide the titlebar
window.titlebarAppearsTransparent = true
window.titleVisibility = .hidden
// Hide all Titlebar Controls
window.standardWindowButton(.miniaturizeButton)?.isHidden = true
window.standardWindowButton(.closeButton)?.isHidden = true
window.standardWindowButton(.zoomButton)?.isHidden = true
// Set the contentView to the SwiftUI ContentView()
window.contentView = NSHostingView(rootView: contentView)
// Make sure the window is movable when grabbing it anywhere
window.isMovableByWindowBackground = true
// Saves frame position between opening / closing
window.setFrameAutosaveName("Main Window")
// Display the window
window.makeKeyAndOrderFront(nil)
window.center()
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
Your window will probably look something like this at this point (if starting with a blank project). You can see the 'Hello world!' isn't exactly centred due to the title bar. ⤵︎
2. Once your NSWindow is setup, time to do the ContentView() ⤵︎
In here you just want to create a wrapper for NSVisualEffectView and add it as a background. AND THEN make sure you remove the safe areas from the view! This makes sure to get rid of any space the title bar was eating up in the view.
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Hello, World!")
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(VisualEffectView(material: .popover, blendingMode: .behindWindow))
// Very important! (You could technically just ignore the top so you do you)
.edgesIgnoringSafeArea(.all)
}
}
/// Takes the image directly behind the window and uses that to create a blurred material. It can technically be added anywhere but most often it's used as a backing material for sidebars and full windows.
struct VisualEffectView: NSViewRepresentable {
let material: NSVisualEffectView.Material
let blendingMode: NSVisualEffectView.BlendingMode
func makeNSView(context: Context) -> NSVisualEffectView {
let visualEffectView = NSVisualEffectView()
visualEffectView.material = material
visualEffectView.blendingMode = blendingMode
visualEffectView.state = NSVisualEffectView.State.active
return visualEffectView
}
func updateNSView(_ visualEffectView: NSVisualEffectView, context: Context) {
visualEffectView.material = material
visualEffectView.blendingMode = blendingMode
}
}
At this point your view should look how you want it without any negative effects! Enjoy <3 (If you're having any problems with this solution leave a comment!)
Resources
Thank you to #eonil for this clever way to keep the rounded corners on. Couldn't have figured this out without this answer ⤵︎
https://stackoverflow.com/a/27613308/13142325
Thank you to lukakerr for making this list of NSWindow styles!
https://github.com/lukakerr/NSWindowStyles

How to create Status Bar icon and menu in macOS using SwiftUI

What is SwiftUI API for creating status bar menus?
Apple seems to use SwiftUI views in Battery & WiFi menus according to the accessibility inspector. Screenshot of a battery menu attached, also its view hierarchy.
EDIT:
Posted the solution as a separate answer.
Since this question received more attention lately, and the only reply doesn't fully solve the issue I would like to repeat the edited part of my question and mark it as resolved.
Edit2: Added an additional piece of code that allows using a SwiftUI view as the status bar icon. Might be handy for displaying dynamic badges.
Found a way to show this in swiftui without an annoying NSPopover. Even though I used AppDelegate's applicationDidFinishLaunching to execute the code, it can be called from any place of your app, even in a SwiftUI lifecycle app.
Here is the code:
func applicationDidFinishLaunching(_ aNotification: Notification) {
// SwiftUI content view & a hosting view
// Don't forget to set the frame, otherwise it won't be shown.
//
let contentViewSwiftUI = VStack {
Color.blue
Text("Test Text")
Color.white
}
let contentView = NSHostingView(rootView: contentViewSwiftUI)
contentView.frame = NSRect(x: 0, y: 0, width: 200, height: 200)
// Status bar icon SwiftUI view & a hosting view.
//
let iconSwiftUI = ZStack(alignment:.center) {
Rectangle()
.fill(Color.green)
.cornerRadius(5)
.padding(2)
Text("3")
.background(
Circle()
.fill(Color.blue)
.frame(width: 15, height: 15)
)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
.padding(.trailing, 5)
}
let iconView = NSHostingView(rootView: iconSwiftUI)
iconView.frame = NSRect(x: 0, y: 0, width: 40, height: 22)
// Creating a menu item & the menu to add them later into the status bar
//
let menuItem = NSMenuItem()
menuItem.view = contentView
let menu = NSMenu()
menu.addItem(menuItem)
// Adding content view to the status bar
//
let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
statusItem.menu = menu
// Adding the status bar icon
//
statusItem.button?.addSubview(iconView)
statusItem.button?.frame = iconView.frame
// StatusItem is stored as a property.
self.statusItem = statusItem
}
Inside the AppDelegate add the following code:
// Create the status item in the Menu bar
self.statusBarItem = NSStatusBar.system.statusItem(withLength: CGFloat(NSStatusItem.variableLength))
// Add a menu and a menu item
let menu = NSMenu()
let editMenuItem = NSMenuItem()
editMenuItem.title = "Edit"
menu.addItem(editMenuItem)
//Set the menu
self.statusBarItem.menu = menu
//This is the button which appears in the Status bar
if let button = self.statusBarItem.button {
button.title = "Here"
}
This will add a Button with a custom Menu to your MenuBar.
Edit - How to use SwiftUI View
As you asked, here is the answer how to use a SwiftUI View.
First create a NSPopover and then wrap your SwiftUI view inside a NSHostingController.
var popover: NSPopover
let popover = NSPopover()
popover.contentSize = NSSize(width: 350, height: 350)
popover.behavior = .transient
popover.contentViewController = NSHostingController(rootView: contentView)
self.popover = popover
Then instead of showing a NSMenu, toggle the popover:
self.statusBarItem = NSStatusBar.system.statusItem(withLength: CGFloat(NSStatusItem.variableLength))
if let button = self.statusBarItem.button {
button.title = "Click"
button.action = #selector(showPopover(_:))
}
With following action:
#objc func showPopover(_ sender: AnyObject?) {
if let button = self.statusBarItem.button
{
if self.popover.isShown {
self.popover.performClose(sender)
} else {
self.popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
}
}
}
MenuBarExtra (macOS Ventura)
In macOS 13.0+ and Xcode 14.0+, the MenuBarExtra struct allows you create a system menu bar, that is similar to NSStatusBar's icons and menus. Use a MenuBarExtra when you want to provide access to commonly used functionality, even when your app is not active.
import SwiftUI
#available(macOS 13.0, *) // macOS Ventura
#main struct StatusBarApp: App {
#State private var command: String = "a"
var body: some Scene {
MenuBarExtra(command, systemImage: "\(command).circle") {
Button("Uno") { command = "a" }
.keyboardShortcut("U")
Button("Dos") { command = "b" }
.keyboardShortcut("D")
Divider()
Button("Salir") { NSApplication.shared.terminate(nil) }
.keyboardShortcut("S")
}
}
}
Getting rid of the App's icon on the Dock
In Xcode's Info tab, choose Application is agent (UIElement) and set its value to YES.

Custom View in Status Bar is Not Appearing Disabled on Secondary Screen

I have an app that uses a custom view in the menu bar of macOS. macOS has a feature that items in the menu bar will appear disabled on a secondary screen (I think an alpha value will be added to the view).
When I remove the custom view from the Button, everything works fine. But when I use my custom view, the view always looks the same, no matter if it is the primary or the secondary monitor.
Even setting the property "appearsDisabled" does not change the look of the view.
This is the code that I am using:
private let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
private var view: HostView?
func applicationDidFinishLaunching(_ aNotification: Notification)
{
self.createMainView()
self.createMenuBarView()
}
fileprivate func createMenuBarView()
{
// Remove all sub views from the view and create new ones.
self.view?.subviews.removeAll()
var width: CGFloat = 0
for device in self.controller.model.devices
{
if let newView = self.createView(for: device.value, x: width)
{
self.view?.addSubview(newView.view)
width += newView.width
}
}
self.view?.frame = NSRect(x: 0, y: 0, width: width, height: MenuBar.height)
self.statusItem.image = nil
self.statusItem.length = width
if let view = self.view
{
// Do I have to set some properties here?
self.statusItem.button?.addSubview(view)
}
}
fileprivate func createMainView()
{
let view = HostView(frame: NSRect(x: 0, y: 0, width: 32.0, height: MenuBar.height))
view.menu = self.menu
self.view = view
}
The problem seems to be that I am adding a NSView to the button of the NSStatusItem as a subview.
self.statusBarItem.button?.addSubview(myView)
When I set my custom view to the view-Property of the NSStatusItem, the view is grayed out on a secondary screen (note that this is deprecated since macOS 10.14).

How to add buttons when NSVisualEffectView is used

I have created a window using NSVisualEffectView to get blur and rounded corners. Like here
The problem is I don't see my button in the window when I have NSVisualEffectView code. If I remove the code, the button is displayed. What is going wrong?
NSVisualEffectView code in AppDelegate.swift:
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
guard let window = NSApplication.shared().windows.first else { return }
let effect = NSVisualEffectView(frame: NSRect(x: 0, y: 0, width: 0, height: 0))
effect.blendingMode = .behindWindow
effect.state = .active
effect.material = .dark
effect.wantsLayer = true
effect.layer?.cornerRadius = 15.0
effect.layer?.masksToBounds = true
window.isOpaque = false
window.backgroundColor = .clear
window.contentView = effect
window.titlebarAppearsTransparent = true
window.titleVisibility = .hidden
}
I have added some buttons in storyboard. When I run the project I don't see any buttons.
When I remove everything from applicationDidFinishLaunching(_ aNotification: Notification) i.e., NSVisualEffectView code, I can see the buttons.
Can anyone tell me what is happening?
I think I should have corrected you in your previous question only but I didn't.
You are using Storyboard so why are you creating NSVisualViewEffect variable in your code?
Search for nsvisualeffectview in the right panel(Utilities panel) where you search for buttons etc. (object library).
Drag it and resize it according to your main view controller.
To add the blur effect and mode, go to "Attribites Inspector" in the "Utilities panel"
and set window.backgroundColor = .clear and window.isOpaque = false
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
guard let window = NSApplication.shared.windows.first else { return }
window.isOpaque = false
window.backgroundColor = .clear
}
Now you can add your buttons, text fields and run the project. You can see all your added elements.
I hope it helps!
window is above the view you are adding buttons to, so the buttons are below the blurred-out window, and are therefore impossible to see. Why not add the visualEffectView to the same view as the buttons? You'd need to insert it below the buttons to make the buttons visible.