我是Cocoa Programming的初学者。 当光标在按钮上时,如何更改NSButton的标题? (不点击)。
I'm beginner of Cocoa Programming. How can I change NSButton's title when cursor is on the button? (without clicking).
最满意答案
如果你看看NSButton的类层次结构,你会发现它来自NSResponder,它是处理鼠标事件的类。
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/nsbutton_Class/Reference/Reference.html
创建一个NSButton的子类并覆盖下面的消息,将标题设置为你想要的:
- (void)mouseEntered:(NSEvent *)theEvent - (void)mouseExited:(NSEvent *)theEvent将它添加到您的初始化程序(根据您的使用情况,可以是awakeFromNib或init消息):
[self addTrackingRect:[self bounds] owner:self userData:NULL assumeInside:YES];请注意,即使当标题第一次显示退出的消息时,鼠标还没有真正进入跟踪区域, 如果您想在第一次进入跟踪区域之前设置第三个标题集,则可能需要为您的课程添加一些状态。
编辑:也许这会有所帮助。
这是头文件“MyButton.h”:
#import <Cocoa/Cocoa.h> @interface MTButton : NSButton { NSTrackingRectTag myTrackingRectTag; } @end很标准的东西。
这是我的源文件。
#import "myButton.h" @implementation MTButton - (void) awakeFromNib { [self setTitle:@"Initial"]; myTrackingRectTag = [self addTrackingRect:[self bounds] owner:self userData:NULL assumeInside:YES]; } - (void) dealloc { [super dealloc]; [self removeTrackingRect:myTrackingRectTag]; } - (void)mouseEntered:(NSEvent *)theEvent { [super mouseEntered:theEvent]; [self setTitle:@"Entered"]; } - (void)mouseExited:(NSEvent *)theEvent { [super mouseExited:theEvent]; [self setTitle:@"Exited"]; } @endIf you look at the class hierarchy for NSButton you'll see that it derives from NSResponder which is the class that handles mouse events.
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/nsbutton_Class/Reference/Reference.html
Create a subclass of NSButton and override the following messages to set the title to what you want:
- (void)mouseEntered:(NSEvent *)theEvent - (void)mouseExited:(NSEvent *)theEventAdd this to your initializer (Either awakeFromNib or your init message, depending on your usage):
[self addTrackingRect:[self bounds] owner:self userData:NULL assumeInside:YES];Note that even when the mouse has not actually entered the tracking area the first time the title will display the exited message. You may want to add some state to your class to if you want a third title set before it enters the tracking area the first time.
EDIT: Maybe this will help.
Here is the header file "MyButton.h":
#import <Cocoa/Cocoa.h> @interface MTButton : NSButton { NSTrackingRectTag myTrackingRectTag; } @endPretty standard stuff.
Here is my source file.
#import "myButton.h" @implementation MTButton - (void) awakeFromNib { [self setTitle:@"Initial"]; myTrackingRectTag = [self addTrackingRect:[self bounds] owner:self userData:NULL assumeInside:YES]; } - (void) dealloc { [super dealloc]; [self removeTrackingRect:myTrackingRectTag]; } - (void)mouseEntered:(NSEvent *)theEvent { [super mouseEntered:theEvent]; [self setTitle:@"Entered"]; } - (void)mouseExited:(NSEvent *)theEvent { [super mouseExited:theEvent]; [self setTitle:@"Exited"]; } @end更多推荐
发布评论