2009-11-09 7 views

答えて

15

ビューのトラッキングエリアをaddTrackingArea(Leopardまたはそれより新しいOS Xを使用している場合)に設定します。マウス入力とマウス終了のイベントが表示されます。

+0

あなたは(...少なくともいくつかの例で)コードでこれを行う方法について説明していただけますか? – mthama

1

以下の回答が多分あります。

class HoverButton: NSButton{ 

var backgroundColor: NSColor? 
var hoveredBackgroundColor: NSColor? 
var pressedBackgroundColor: NSColor? 

private var hovered: Bool = false 

override var wantsUpdateLayer:Bool{ 
    return true 
} 

required init?(coder: NSCoder) { 
    super.init(coder: coder) 
    self.commonInit() 
} 

override init(frame frameRect: NSRect) { 
    super.init(frame: frameRect) 
    self.commonInit() 
} 

func commonInit(){ 
    self.wantsLayer = true 
    self.createTrackingArea() 
    self.hovered = false 
    self.hoveredBackgroundColor = NSColor.selectedTextBackgroundColor() 
    self.pressedBackgroundColor = NSColor.selectedTextBackgroundColor() 
    self.backgroundColor = NSColor.clearColor() 
} 

private var trackingArea: NSTrackingArea! 
func createTrackingArea(){ 
    if(self.trackingArea != nil){ 
     self.removeTrackingArea(self.trackingArea!) 
    } 
    let circleRect = self.bounds 
    let flag = NSTrackingAreaOptions.MouseEnteredAndExited.rawValue + NSTrackingAreaOptions.ActiveInActiveApp.rawValue 
    self.trackingArea = NSTrackingArea(rect: circleRect, options: NSTrackingAreaOptions(rawValue: flag), owner: self, userInfo: nil) 
    self.addTrackingArea(self.trackingArea) 
} 

override func mouseEntered(theEvent: NSEvent) { 
    self.hovered = true 
    NSCursor.pointingHandCursor().set() 
    self.needsDisplay = true 
} 

override func mouseExited(theEvent: NSEvent) { 
    self.hovered = false 
    NSCursor.arrowCursor().set() 
    self.needsDisplay = true 
} 

override func updateLayer() { 
    if(hovered){ 
     if (self.cell!.highlighted){ 
      self.layer?.backgroundColor = pressedBackgroundColor?.CGColor 
     } 
     else{ 
      self.layer?.backgroundColor = hoveredBackgroundColor?.CGColor 
     } 
    } 
    else{ 
     self.layer?.backgroundColor = backgroundColor?.CGColor 
    } 
} 

}

リンク:https://github.com/fancymax/HoverButton

関連する問題