0

试图创建一个自定义NSSlider. 覆盖更改旋钮外观的drawKnob()方法,NSSliderCell但这样做会以某种方式断开旋钮位置与用户与滑块的交互之间的联系。

在经常引用的目标 C 示例(https://github.com/lucasderraugh/LADSlider)中,看起来当您覆盖时,drawKnob()您需要显式处理该startTracking方法,但我还没有找到适合我的解决方案- 目前我只是将单元格的 startTracking 'at' 属性设置为滑块的当前值,但不确定正确的方法是什么。

相当多的例子包括单元格的自定义初始化程序中的 NSCoder 参数 - 我不明白为什么,但这可能与确保旋钮显示和实际滑块值之间的连接有关?

import Cocoa

class ViewController: NSViewController {

    var seekSlider = NSSlider()
    var seekSliderCell = SeekSliderCell()

    override func viewDidLoad() {
        
        super.viewDidLoad()
        seekSlider = NSSlider(target: self, action: #selector(self.seek(_:)))
        seekSlider.cell = seekSliderCell
        seekSlider.cell?.target = self
        seekSlider.cell?.action = #selector(self.seek(_:))
        seekSlider.isEnabled = true
        seekSlider.isContinuous = true
        view.addSubview(seekSlider)
    }
    
    @objc func seek(_ sender: NSObject) {
        
        let val = seekSlider.cell?.floatValue
        let point = NSPoint(x: Double(val!), y: 0.0)
        seekSlider.cell?.startTracking(at: point, in: self.seekSlider)
    }
}

class SeekSliderCell: NSSliderCell {
    
//  required init(coder aDecoder: NSCoder) {
//      super.init(coder: aDecoder)
//  }
    
    override func drawKnob() {
        
        let frame = NSRect(x: 0.0, y: 6.0, width: 20.0, height: 10.0)
        let c = NSColor(red: 0.9, green: 0.0, blue: 0.6, alpha: 1.0)
        c.setFill()
        NSBezierPath.init(roundedRect: frame, xRadius: 3, yRadius: 3).fill()
    }

    override func startTracking(at startPoint: NSPoint, in controlView: NSView) -> Bool {

       return true
    }
}


4

1 回答 1

1

国家的文件drawKnob()

特殊注意事项 如果您创建 NSSliderCell 的子类,请不要覆盖此方法。改为覆盖 drawKnob(_:)。

代替

func drawKnob()

覆盖

func drawKnob(_ knobRect: NSRect)

例子:

class ViewController: NSViewController {

    var seekSlider = NSSlider()
    var seekSliderCell = SeekSliderCell()

    override func viewDidLoad() {
        super.viewDidLoad()
        seekSlider = NSSlider(target: self, action: #selector(self.seek(_:)))
        seekSlider.cell = seekSliderCell
        seekSlider.cell?.target = self
        seekSlider.cell?.action = #selector(self.seek(_:))
        seekSlider.isEnabled = true
        seekSlider.isContinuous = true
        view.addSubview(seekSlider)
    }

    @objc func seek(_ sender: NSObject) {
        let val = seekSlider.cell?.floatValue
        print("\(String(describing: val))")
    }

}

class SeekSliderCell: NSSliderCell {

    override func drawKnob(_ knobRect: NSRect) {
        var frame = NSRect(x: 0.0, y: 6.0, width: 20.0, height: 10.0)
        frame.origin.x = knobRect.origin.x + (knobRect.size.width - frame.size.width) / 2
        frame.origin.y = knobRect.origin.y + (knobRect.size.height - frame.size.height) / 2
        let c = NSColor(red: 0.9, green: 0.0, blue: 0.6, alpha: 1.0)
        c.setFill()
        NSBezierPath.init(roundedRect: frame, xRadius: 3, yRadius: 3).fill()
    }

}
于 2022-03-03T13:57:27.417 回答