Search code examples
macosnsslider

How to change NSSlider tickmarks color?


I know should change the function drawTickMarks,but what should I do to change tickmarks color?


Solution

  • If you want them in different color, draw them in a different color.

    Having an empty implementation of drawTickMarks() draws nothing.

    enter image description here

    Subclass NSSliderCell and set the cell class.

    Then provide a drawing routine in drawTickMarks()

    class CustomSliderCell: NSSliderCell {
    
        override func drawTickMarks() {
    
            guard let slider = controlView as? NSSlider, slider.numberOfTickMarks > 0 else {
                return
            }
    
            let tickWidth: CGFloat = 5
            let horizontalinset: CGFloat = 5
            let verticalinset: CGFloat = 1
            let drawRect = slider.bounds.insetBy(dx: horizontalinset, dy: verticalinset) //squish in slightly
            let step = drawRect.width/CGFloat(numberOfTickMarks-1) //classic fenceposts problem
            var mark = CGFloat(0)
            for _ in 0..<numberOfTickMarks {
                let blob = NSBezierPath(roundedRect: NSRect(x: mark + horizontalinset , y:verticalinset, width: tickWidth, height: tickWidth*2), xRadius: tickWidth/2.0, yRadius: tickWidth/2.0)
                NSColor.green.set()
                blob.fill()
                NSColor.darkGray.set()
                blob.stroke()
                mark += step
            }
        }
    
    }
    

    This one is a demo and far from perfect but should give you an ideas of what is needed.

    enter image description here