问题描述
|
我正在为自定义渲染创建自定义“ 0”。
现在,我想根据鼠标是否在按钮上方来选择不同的外观。我如何获得此信息?
谢谢并恭祝安康,
解决方法
这是我为我创造的完美作品...
步骤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\");
}
,斯威夫特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函数中编写一个切换用例或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!\")
}
}
}
,您需要子类化NSButton类(甚至更好的是NSButtonCell类)。
就像贾斯汀说的那样,如果您使用两种方法
- (void)mouseEntered:(NSEvent *)theEvent;
- (void)mouseExited:(NSEvent *)theEvent;
当鼠标进入和退出该区域时应调用它们。您可能还需要重新创建跟踪区域,请看此处:
- (void)updateTrackingAreas
对于淡入和淡出效果,我使用了动画器和Alpha值,例如:
[self animator]setAlphaValue:0.5];
,在NSResponder中声明的一个很好的起点:
- (void)mouseEntered:(NSEvent *)theEvent;
- (void)mouseExited:(NSEvent *)theEvent;
特别是,按钮单元格的容器(不是单元格本身)是NSResponder。
,对于那些喜欢子类化的人,您也可以自己制作NSButton
并在其中分配NSTrackingArea
。
感谢Joey Zhou,这是一种非常简单而优雅的方法:https://github.com/Swift-Kit/JZHoverNSButton
它是用Swift 2编写的,但是XCode会自动在Swift 3-4中翻译它,没有任何问题。
希望它可以帮助某人