2016-02-25 66 views
0

我想定製myButton,以便在mouseDown發生時更改背景顏色,並在調用mouseUp時返回默認顏色。自定義NSButton。點擊時如何改變顏色

override func mouseDown(theEvent: NSEvent) { 
    super.mouseDown(theEvent) 
    self.bgColor = NSColor(hex: 0x4A7AA1) 
    self.textColor = NSColor.darkGrayColor() 
    self.needsDisplay = true 
    self.mouseUp(theEvent) 
} 

override func mouseUp(theEvent: NSEvent) { 
    self.textColor = NSColor.whiteColor() 
    self.bgColor = NSColor(hex: 0x6AAFE6, alpha: 0.95) 
} 

我試着運行這段代碼,但鼠標關閉時所有視圖都沒有重繪。我如何在myButton上執行此功能:NSButton類?

回答

0

您只需在特定視圖中覆蓋drawRect()即可。 在drawRect中,您可以檢查按鈕是否突出顯示。

func drawRect(dirtyRect: NSRect) { 
    super.drawRect(dirtyRect) 
    if self.highlighted { 
     // Do custom drawing. 
    } 
} 

您不需要檢測mouseDown就行了。 drawRect將自動調用