2013-11-01 62 views
2

我試圖在5個值的可可中實現自定義滑塊。看到我的演示項目,可以在這裏下載:http://s000.tinyupload.com/index.php?file_id=07311576247413689572如何自定義NSSlider

Custom Slider

我子類的NSSliderCell和實施方法,如drawKnob:(NSRect)knobRectdrawBarInside:(NSRect)cellFrame flipped:(BOOL)flipped

我遇到了一些問題:

  1. 我不能定位旋鈕正確地關於背景圖像。我知道我可以改變旋鈕的框架,並且我嘗試了一些計算來正確定位旋鈕,但是我無法使它適用於我的自定義滑塊。有人能幫助我嗎?
  2. 我的自定義滑塊背景的高度是41px。在drawBarInside:(NSRect)cellFrame flipped:(BOOL)flipped中,我也將幀的高度更改爲41px,但整個背景都不可見。爲什麼?
  3. 我注意到包含的圖像(背景和旋鈕)垂直翻轉。爲什麼?請注意,與底部相比,邊框頂部在背景中較暗,但在繪製背景時會反轉。

回答

2
  1. 我發現你的旋鈕矩形的x座標位置的計算錯誤:你以前,你應該使用寬度圖像的高度。

  2. 單元格繪圖正在被剪裁到控件的框架中。也許你可以在你的細胞覺醒時擴大控制框架。

  3. 您需要使用NSImage方法drawInRect:fromRect:operation:fraction:respectFlipped:hints:,並通過YES參數respectFlipped:。 Apple的控件通常使用翻轉的座標。

補充:在awakeFromNib中展開框架看起來不起作用,框架會恢復原狀。這是有用的東西。而不是覆蓋drawBarInside:flipped:,添加此覆蓋:

- (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]; 
} 
+0

謝謝。 1 + 3解決了我的問題。我仍然有一些麻煩試圖改變身高。你能否給我一個例子? – dhrm

+0

如果我使用AutoLayout並在我的* nib *中爲我的NSSlider添加一個高度約束到66,那麼看起來我能夠看到整個單元格。爲什麼這個價值? – dhrm

+0

不知道爲什麼自動佈局設置會起作用。一個例子被添加到我的答案。 – JWWalker