How to configure NSSlider

I am trying to implement a custom slider in Cocoa with 5 values. See my demo project, which can be downloaded here: http://s000.tinyupload.com/index.php?file_id=07311576247413689572 .

Custom slider

I subclassed NSSliderCell and implemented methods like drawKnob:(NSRect)knobRect and drawBarInside:(NSRect)cellFrame flipped:(BOOL)flipped , etc.

I am having some problems:

  • I cannot correctly position the handle relative to the background image. I know that I can change the frame of the handle, and I tried to do some calculations to position the handle correctly, but I cannot make it work for my custom slider. Can someone help me with this?
  • The height of my custom slider background is 41px. In drawBarInside:(NSRect)cellFrame flipped:(BOOL)flipped I change the frame height to 41px, but the whole background is not displayed. Why?
  • I noticed that the included images (background and pen) are inverted vertically. What for? Note that the top of the border is darker in the background compared to the bottom, but when you draw the background, it changes direction.
+2
objective-c cocoa macos nsslider
source share
1 answer
  • I found an error in calculating the x position of the handle rectangle: you used the height of the image in which you had to use the width.

  • The cell picture is snapped to the frame of the control. Perhaps you can expand the control frame when your cell awakens.

  • You need to use the NSImage drawInRect:fromRect:operation:fraction:respectFlipped:hints: and pass YES for the respectFlipped: parameter. Apple usually uses inverted coordinates.

Added: The frame extension in awakeFromNib does not work, the frame is returned. Something is working here. Instead of overriding drawBarInside:flipped: add this overriding:

 - (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView { NSRect controlFrame = [controlView frame]; float bgHeight = self.backgroundImage.size.height; if (controlFrame.size.height < bgHeight) { controlFrame.size.height = bgHeight; [controlView setFrame: controlFrame]; } [self.backgroundImage drawInRect: [controlView bounds] fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0 respectFlipped: YES hints: NULL]; [self drawKnob]; } 
+2
source share

All Articles