本文介绍了如何创建状态栏图标&在MacOS Big Sur中使用SwiftUI进行菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是用于创建状态栏菜单的SwiftUI API?

What is SwiftUI API for creating status bar menus?

Apple似乎在Battery&中使用SwiftUI视图.根据辅助功能检查器提供的WiFi菜单.附带的电池菜单的屏幕截图,以及其视图层次结构.

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.

发布解决方案作为单独的答案.

Posted solution as a separate answer.

推荐答案

由于该问题最近引起了更多关注,并且唯一的答复不能完全解决问题,因此我想重复问题的编辑部分并将其标记为解决.

Since this question got 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.

找到了一种显示swiftui而不烦人的NSPopover的方法.如果您使用SwiftUI应用生命周期,则需要具有"AppDelegate"或"NSApplicationDelegateAdaptor".然后创建NSMenu并添加可以具有自定义视图的NSMenuItem.

Found a way to show swiftui without annoying NSPopover. You'd need to have 'AppDelegate' or 'NSApplicationDelegateAdaptor' in case you use SwiftUI App lifecycle. Then you create NSMenu and add NSMenuItem that can have a custom view.

这是代码:

    let contentView = VStack {
        Text("Test Text")
        Spacer()
        HStack {
            Text("Test Text")
            Text("Test Text")
        }
        Spacer()
        Text("Test Text")
    }
    let view = NSHostingView(rootView: contentView)
    // Don't forget to set the frame, otherwise it won't be shown.
    view.frame = NSRect(x: 0, y: 0, width: 200, height: 200)
    
    let menuItem = NSMenuItem()
    menuItem.view = view
    
    let menu = NSMenu()
    menu.addItem(menuItem)
    
    // StatusItem is stored as a class property.
    self.statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
    self.statusItem?.menu = menu
    self.statusItem?.button?.title = "Test"

这篇关于如何创建状态栏图标&在MacOS Big Sur中使用SwiftUI进行菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 08:18