对NSButton的简单鼠标悬停效果

时间:2011-05-23 08:37:59

标签: cocoa nsbutton nsbuttoncell

我正在为自定义呈现创建自定义NSButtonCell

现在,我希望根据鼠标是否在按钮上方有不同的方面。我怎样才能获得这些信息?

谢谢和问候,

7 个答案:

答案 0 :(得分:30)

这是我为我创造并完美地工作的......

步骤1:创建带跟踪区域的按钮

 NSButton *myButton = [[NSButton alloc] initWithFrame:NSMakeRect(100, 7, 100, 50)];
[myButton setTitle:@"sample"];

[self.window.contentView addSubview:myButton];
// Insert code here to initialize your application
NSTrackingArea* trackingArea = [[NSTrackingArea alloc]
                                initWithRect:[myButton bounds]
                                options:NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways
                                owner:self userInfo:nil];
[myButton addTrackingArea:trackingArea];

步骤:2实施以下方法

- (void)mouseEntered:(NSEvent *)theEvent{
NSLog(@"entered");
[[myButton cell] setBackgroundColor:[NSColor blueColor]];


}

- (void)mouseExited:(NSEvent *)theEvent{
[[myButton cell] setBackgroundColor:[NSColor redColor]];
NSLog(@"exited");

}

答案 1 :(得分:10)

斯威夫特3:

使用代码创建按钮或只使用它的@IBOutlet。 然后定义按钮的鼠标悬停跟踪区域(悬停):

let area = NSTrackingArea.init(rect: yourButtonName.bounds,
                               options: [.mouseEnteredAndExited, .activeAlways], 
                               owner: self, 
                               userInfo: nil)
yourButtonName.addTrackingArea(area)

然后覆盖mouseEntered和mouseExited,在这些函数中设置您想要更改的内容(按钮颜色,按钮图像,按钮文本,..):

override func mouseEntered(with event: NSEvent) {
    print("Entered: \(event)")
}

override func mouseExited(with event: NSEvent) {
    print("Exited: \(event)")
}

如果您有多个按钮(每个按钮都添加了跟踪区域)并且您需要确定哪个按钮触发了mouseEntered事件,您可以为此添加一些userInfo信息,而不是:

userInfo: nil

在userInfo中为每个按钮添加自定义按钮名称,例如:

userInfo: ["btnName": "yourButtonName"]

然后你可以在mouseEntered和mouseExited函数中编写一个switch-case或if语句,如下所示:

override func mouseEntered(with event: NSEvent) {
        // Identify which button triggered the mouseEntered event
        if let buttonName = event.trackingArea?.userInfo?.values.first as? String {
            switch (buttonName) {
            case "yourButtonName":
                //do whatever you want for this button..
            case "anotherButtonName":
                //do whatever you want for this button..
            default:
                print("The given button name: \"\(buttonName)\" is unknown!")
            }
        }
    }

答案 2 :(得分:9)

您需要对NSButton类进行子类化(甚至更好的是NSButtonCell类)。 正如贾斯汀所说,如果你把这两种方法

- (void)mouseEntered:(NSEvent *)theEvent;
- (void)mouseExited:(NSEvent *)theEvent;

当鼠标进入和退出该区域时,应该调用它们。您可能还需要重新创建跟踪区域,请查看此处:

- (void)updateTrackingAreas

对于淡入和淡出效果,我使用动画师和alpha值进行游戏,例如:

[self animator]setAlphaValue:0.5]; 

答案 3 :(得分:3)

一个很好的起点,在NSResponder中声明:

- (void)mouseEntered:(NSEvent *)theEvent;
- (void)mouseExited:(NSEvent *)theEvent;

具体来说,按钮单元的容器(不是单元本身)是NSResponder。

答案 4 :(得分:0)

对于那些喜欢子类化的人,您也可以制作自己的GrabAudio gr = new GrabAudio(0, 1024, mp.getAudioSessionId()); gr.start(); byte[] b = gr.getRawData(); gr.release(); Log.i("test11", "b:" + Arrays.toString(b)); 并在其中分配NSButton

由于 Joey Zhou https://github.com/Swift-Kit/JZHoverNSButton

,这是一种非常简单而优雅的方法

它是用 Swift 2 编写的,但是XCode会自动将它用 Swift 3-4 进行翻译。

希望它可以帮助某人

答案 5 :(得分:0)

这是一个简单的代码,可以跟踪某些控件(图像,标签等)上的mouse entermouse exit事件:

@IBOutlet weak var myImage: NSImageView!
@IBOutlet weak var myLabel: NSTextField!

override func viewDidLoad() {
    super.viewDidLoad()

    let area1 = myTrakingArea(control: self.myImage)
    let area2 = myTrakingArea(control: self.myLabel)
    self.myImage.addTrackingArea(area1)
    self.myLabel.addTrackingArea(area2)
}

func myTrakingArea(control: NSControl) -> NSTrackingArea {
    return NSTrackingArea.init(rect: control.bounds,
    options: [.mouseEnteredAndExited, .activeAlways],
    owner: control,
    userInfo: nil)
}

override func mouseEntered(with event: NSEvent) {
    if let owner = event.trackingArea?.owner as? NSControl {
        let id : String = owner.identifier!.rawValue

        switch id {
        case self.myLabel.identifier!.rawValue:
                print("Entered Quit Label")
        case self.myImage.identifier!.rawValue:
                print("Entered Quit Image")
            default:
                print("Entered ???")
        }
    }
}

override func mouseExited(with event: NSEvent) {
    if let owner = event.trackingArea?.owner as? NSControl {
        let id : String = owner.identifier!.rawValue

        switch id {
        case self.myLabel.identifier!.rawValue:
                print("Exited Quit Label")
        case self.myImage.identifier!.rawValue:
                print("Exited Quit Image")
            default:
                print("Exited ???")
        }
    }
}

答案 6 :(得分:0)

带有回调的Swift 5版本,超级易于使用:

final class HoverButton: NSButton {

    private let callback: (HoverButton, Bool) -> Void

    init(callback: @escaping (HoverButton, Bool) -> Void) {
        self.callback = callback
        super.init(frame: .zero)
        let area = NSTrackingArea(rect: bounds, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil)
        addTrackingArea(area)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func mouseEntered(with event: NSEvent) {
        super.mouseEntered(with: event)
        callback(self, true)
    }

    override func mouseExited(with event: NSEvent) {
        super.mouseExited(with: event)
        callback(self, false)
    }

}

用法:

let button = HoverButton { button, isHovered in
    button.animator().alphaValue = isHovered ? 1 : 0.5
}