是否有一个可以设置的标志,当它被鼠标悬停时会导致Cocoa按钮突出显示。我需要以编程方式在OSX上使用目标C.
答案 0 :(得分:15)
使用 addTrackingArea 为视图设置跟踪区域(前提是您使用的是Leopard或更新的OS X)。您将在鼠标输入和鼠标退出时获得事件。
答案 1 :(得分: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
}
}
}
答案 2 :(得分:0)
也可以覆盖按钮单元,以将鼠标的进入/退出事件传播到视图。我没有测试所有按钮样式,而是使用了嵌入式样式。
如果drawBezel
为true,则在mouseEnter上调用showsBorderOnlyWhileMouseInside
函数。
这就是为什么我只是覆盖它,并在按钮中管理自定义显示行为的原因。
class myButtonCell: NSButtonCell {
override func mouseEntered(with event: NSEvent) {
controlView?.mouseEntered(with: event)
// Comment this to remove title highlight (for button style)
super.mouseEntered(with: event)
}
override func mouseExited(with event: NSEvent) {
controlView?.mouseExited(with: event)
// Comment this to remove title un-highlight (for recessed button style)
// Here, we un-hilight the title only if the button is not selected
if state != .on { super.mouseExited(with: event) }
}
// removes the default highlight behavior
override func drawBezel(withFrame frame: NSRect, in controlView: NSView) {}
}
// Set the cell class to MyButtonCell in interface builder
class MyButton: NSButton {
var mouseIn: Bool = false { didSet {
// Up to you here - setNeedsDisplay() or layer update
}}
override func mouseEntered(with event: NSEvent) { mouseIn = true }
override func mouseExited(with event: NSEvent) { mouseIn = false }
}