2015-04-01 175 views
2

我在Mac應用程序的工作。我試圖做一個簡單的動畫,使NSButton向下移動。動畫效果非常好,但是當我這樣做時,我的NSButton的背景顏色由於某種原因而消失。這裏是我的代碼:NSAnimation刪除按鈕的背景顏色

// Tell the view to create a backing layer. 
additionButton.wantsLayer = YES; 

// Set the layer redraw policy. This would be better done in 
// the initialization method of a NSView subclass instead of here. 
additionButton.layerContentsRedrawPolicy = NSViewLayerContentsRedrawOnSetNeedsDisplay; 

[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) { 
    context.duration = 1.0f; 
    additionButton.animator.frame = CGRectOffset(additionButton.frame, 0.0, -20.0); 
    //additionButton.frame = CGRectOffset(additionButton.frame, 0.0, -20.0); 
} completionHandler:nil]; 

按鈕向下移動的動畫:

enter image description here

按鈕移動後向下動畫:

enter image description here

更新1

只是爲了說清楚,我沒有在按鈕中使用背景圖片。我使用的是背景NSColor我在viewDidLoad方法設置像這樣:

[[additionButton cell] setBackgroundColor:[NSColor colorWithRed:(100/255.0) green:(43/255.0) blue:(22/255.0) alpha:1.0]]; 
+0

的圖像不顯示 – 2015-04-01 05:58:15

+0

@ysaditya但我不使用圖片爲我NSButton的背景。我用一個簡單的NSColor填充了它。 – Supertecnoboff 2015-04-01 05:59:24

+0

你正在使用哪種按鈕類型(例如瞬時推入等) – 2015-04-01 06:09:17

回答

1

我想這是一個錯誤了AppKit。有幾種方法可以解決這個問題。


解決方法1:

不要使用圖層。你動畫按鈕似乎是小,你也許能逃脫使用非層支持的動畫,仍然有它看起來體面。該按鈕將在動畫的每個步驟中重新繪製,但會正確動畫。這意味着,這實在是所有你需要做的:

[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {   
    additionButton.animator.frame = CGRectOffset(additionButton.frame, 0, -20); 
} completionHandler:nil]; 

解決方法2:

設置圖層上的背景色。

additionButton.wantsLayer = YES; 
additionButton.layer.backgroundColor = NSColor.redColor.CGColor; 
additionButton.layerContentsRedrawPolicy = NSViewLayerContentsRedrawOnSetNeedsDisplay; 

[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {   
    additionButton.animator.frame = CGRectOffset(additionButton.frame, 0, -20); 
} completionHandler:nil]; 

解決方法3:

子類NSButtonCell,並實現-drawBezelWithFrame:inView:,繪製背景色也。請記住,包含該按鈕的父視圖應該是層次支持的,否則該按鈕仍然會在每一步重繪。

+0

中設置屬性非常感謝你!!!!!我決定採用解決方法2,因爲在閱讀完您的真棒網站之後,您說過後面的動畫效果更加平滑。再次感謝,並感謝他們花時間查看我在Twitter上發送的問題。這個答案已經打勾並upvoted:D – Supertecnoboff 2015-04-02 05:42:38

+3

良好的交易。確保按鈕具有圖層背景的父級,否則動畫將不像您期望的那樣平滑。 – 2015-04-02 07:56:09

+0

謝謝。會做。 – Supertecnoboff 2015-04-02 16:02:54