How to place Horizontal Slider in NSMenu (Swift 3, Xcode 8)

感情迁移 提交于 2019-12-07 17:35:45

问题


As of macOS Sierra the volume menu bar item provides a horizontal slider item to change the system's volume:

I'd like to adopt this concept for my own application and came up with the following class:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!
    let statusItem = NSStatusBar.system().statusItem(withLength: -2)

    func applicationDidFinishLaunching(_ aNotification: Notification) {

        let menu = NSMenu()
        let menuItem = NSMenuItem()
        let statusSlider = NSSlider()

        menu.addItem(NSMenuItem(title: "Slider:", action: nil, keyEquivalent: ""))

        menuItem.title = "Slider 1"
        menuItem.view = statusSlider
        menu.addItem(menuItem)

        menu.addItem(NSMenuItem.separator())

        menu.addItem(NSMenuItem(title: "Quit", action: Selector("terminate:"), keyEquivalent: "q"))

        statusItem.image = NSImage(named: "NSStatusAvailable")
        statusItem.menu = menu
    }
}

But there is no slider showing up in the menu. Has anybody a clue what I did wrong?


回答1:


The initial frame size of NSSlider is zero. You need to set the size before adding it to a menu item.

statusSlider.setFrameSize(NSSize(width: 160, height: 16))


来源:https://stackoverflow.com/questions/39890861/how-to-place-horizontal-slider-in-nsmenu-swift-3-xcode-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!