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

1

8

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

macOS Sierra volume menu

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?

enter image description here

Syrinx answered 6/10, 2016 at 8:12 Comment(1)
If you are using IB you can add a regular menu item and connect its view property. That ways you could use outolayoutSouthwestwardly
C
11

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))
Calcimine answered 6/10, 2016 at 16:12 Comment(2)
I was finally able to get a NSColorWell in my menu after specifying a frame size.Brande
How to center the slider horizontally in the NSMenuItem container?Bricklayer

© 2022 - 2025 — McMap. All rights reserved.