【问题标题】:Custom View inside NSMenu Item in SWIFTSWIFT 中 NSMenu 项内的自定义视图
【发布时间】:2021-03-18 08:40:56
【问题描述】:

我想在 MacOS 的任务栏 Swift 应用程序中构建一个两行菜单项,它的行为就像一个普通的菜单项,只是带有附加信息。我设法让菜单和任务栏应用程序运行,但菜单项内的自定义视图失败了。

理想情况下,如果在这种情况下可能的话,我想使用 SwiftUI View 结构,并完全避免使用 XIB 文件。

更新:我尝试使用 NSHostingView 进行集成,但结果相同 - 菜单项不会显示

AppDelegate

func applicationDidFinishLaunching(_ aNotification: Notification) {
   self.statusBarItem = NSStatusBar.system.statusItem(withLength:
        CGFloat(NSStatusItem.variableLength))
   // set the menu and the task bar image
   self.statusBarItem.menu = TaskBarMenu()
   self.statusBarItem.button?.image = NSImage(named: "icon-normal")
}

任务栏菜单

class TaskBarMenu: NSMenu {
  override init(title: String) {
    super.init(title: title)
    let testMenu = NSMenuItem()
    testMenu.view = TaskbarMenuView()

    items = [
       NSMenuItem(title:"Test Item", action: #selector(NSApplication.hide(_:)), keyEquivalent: "h"),
       NSMenuItem.separator(),
       testMenu
    ]
  }
  
  required init(coder: NSCoder) {
    super.init(coder : coder)
  }
}

任务栏菜单视图

class TaskbarMenuView: NSView {
    let nameTextField: NSTextField = {
        let textField = NSTextField()
        textField.stringValue = "Some custom name"
        return textField
    }()

    override init(frame: CGRect) {
            super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
           fatalError("init(coder:) has not been implemented")
    }
}

【问题讨论】:

标签: swift macos swiftui nsmenuitem


【解决方案1】:

我发现了问题:需要设置view的frame,否则什么都不显示。

How to create status bar icon & menu with SwiftUI like in macos Big Sur

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多