使用Swift

时间:2016-08-15 06:57:15

标签: swift nsview nsimage nsmenu nsmenuitem

我以编程方式创建了一个NSSlider,并在NSMenuItem中实现了它:

    let menuVolumeSliderItem = NSMenuItem()
    let menuVolumeSlider = NSSlider()

    menuVolumeSlider.sliderType = NSSliderType.linear
    menuVolumeSlider.isEnabled = true
    menuVolumeSlider.isContinuous = true
    menuVolumeSlider.action = #selector(AppDelegate.doSomething)
    menuVolumeSlider.minValue = 0.0
    menuVolumeSlider.maxValue = 1.0
    menuVolumeSlider.floatValue = 0.5
    menuVolumeSlider.frame.size.width = menu.size.width
    menuVolumeSlider.frame.size.height = 20.0

    menuVolumeSliderItem.view = menuVolumeSlider
    menu.addItem(menuVolumeSliderItem)

基本上,它的工作就像一个魅力:

enter image description here

但我想要实现的结果是Slider,在Slider的左/右边缘有一个最小/最大图像,如下所示:

enter image description here

如何实现这样的NSMenuItem?

修改

我已经创建了一个自定义NSView:

    let view = NSView()
    view.frame.size.width = menu.size.width
    view.frame.size.height = 25.0

...然后创建了一个NSImage ......

    let img = NSImageView()
    img.frame.size.width = 16.0
    img.frame.size.height = 16.0
    img.image = NSImage(named: "NSStatusAvailable")!

...并将menuVolumeSliderimg添加到我的自定义视图中:

    view.addSubview(img)
    view.addSubview(menuVolumeSlider)
    menuVolumeSliderItem.view = view
    menu.addItem(menuVolumeSliderItem)

......它有效!但有人可以给我一个提示如何改变子视图的位置吗?

enter image description here

1 个答案:

答案 0 :(得分:1)

创建一个包含滑块和两个图像的NSView。然后将menuVolumeSliderItem.view设置为NSView。