1
votes

I need to subclass NSSliderCell to customise its appearance. I had no problem with the bar, I overrode

- (void)drawBarInside:(NSRect)aRect flipped:(BOOL)flipped

and it works as expected.

- (void)drawKnob:(NSRect)knobRect

works as well, but I want a smaller knob, and resizing the NSRect isn't an option, because I have an unwanted space either on the right or on the left (or both, if I center my custom knob).

Reading the documentation, I should override

- (void)drawKnob

to calculate the rect in which the knob should be drawn, then call drawKnob: The problem is that, trying to get the cellSize to compute where I should draw the knob, I get an absurd width : 40000

How can I get the right width? NSSliderCell is a subclass of NSCell, so I can't access frame/bounds.

1
Try overriding -knobThickness as well. I can't remember if that's necessary or not.Wevah
Thank you @Wevah, it works!Alessandro
I'll add it as an answer, then. >_>Wevah
@Wevah, setting knobThickness doesn't work, knobRect always returns same width, whatever I return from -knobThickness method. I actually solved adding a width property to NSSliderCell and overriding - (NSRect)knobRectFlipped:(BOOL)flippedAlessandro
Yeah, that seems more correct. Whoops!Wevah

1 Answers

3
votes

I actually managed to customise NSSlider knob appearance adding a width property to NSSliderCell and overriding - (NSRect)knobRectFlipped:(BOOL)flipped this way:

- (NSRect)knobRectFlipped:(BOOL)flipped {
CGFloat knobCenterPosition = roundf(size.width * self.floatValue / self.maxValue);
// knob should always be entirely visible
knobCenterPosition = MIN(MAX(knobCenterPosition, roundf(KNOB_WIDTH / 2) + KNOB_INSET), size.width - (roundf(KNOB_WIDTH / 2) + KNOB_INSET));
return  NSMakeRect(knobCenterPosition - roundf(KNOB_WIDTH / 2), 0, KNOB_WIDTH, self.cellSize.height);

}

I need to change knobCenterPosition when the knob would overlap the right or left border of the slider (KNOB_WIDTH and KNOB_INSET are self explaining macros).