Menu

SwiftUI's MenuBarExtra writes isInserted back on every update (and how that cost me 97% CPU)
📰

SwiftUI's MenuBarExtra writes isInserted back on every update (and how that cost me 97% CPU)

DEV Community: swift·Usukhbayar·about 12 hours ago
#ssCjD97a
#devtoswift#devto#dev#showicon#back
Reading 0:00
15s threshold

Scrollr is a small open-source menu bar app that reverses mouse wheel scrolling but leaves the trackpad alone. It has a "Show in menu bar" toggle, and opening the app again from Finder should bring a hidden icon back. That simple feature hit two SwiftUI surprises in a row.

The setup everyone uses

// App @AppStorage ( "showIcon" ) private var showIcon = true MenuBarExtra ( isInserted : $showIcon ) { . . . }

// AppDelegate func applicationShouldHandleReopen ( _ sender : NSApplication , hasVisibleWindows : Bool ) -> Bool { UserDefaults . standard . set ( true , forKey : "showIcon" ) return true }

Enter fullscreen mode

Exit fullscreen mode

It passed my tests, because I always started with the icon visible and hid it from Settings. Then I tried the case I'd skipped: launch with the icon already hidden, then reopen. The handler ran (I logged it), the value became true , and it was false again within 100 ms. Deferring the write by 0.3 s didn't help.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.