How should I get the mouse event in the Cocoa window controller or I should try another way around?
I am designing a feature where the text field transforms into a big plus sign when the mouse is hovering over its area.
I would recommend subclassing NSTextField and handling the events there. As trojanfoe said, it has mouse-handling built in. Plus the feature you describe sounds like something that you might use again, in the same app or another. Just setting the class to your custom NSTextField will save time.
It could look something like this:
DCOHoverTextField.h
#import <Cocoa/Cocoa.h>
/** An `NSTextField` subclass that supports mouse entered/exited events.
*/
@interface DCOHoverTextField : NSTextField
@end
DCOHoverTextField.m
#import "DCOHoverTextField.h"
@interface DCOHoverTextField()
/* Holds the tracking area for the `NSTextField`. */
@property (strong) NSTrackingArea *trackingArea;
@end
@implementation DCOHoverTextField
- (void)updateTrackingAreas {
// Remove tracking area if we have one
if(self.trackingArea) {
[self removeTrackingArea:self.trackingArea];
}
// Call super
[super updateTrackingAreas];
// Create a new tracking area
self.trackingArea = [[NSTrackingArea alloc] initWithRect:self.bounds
options: NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways
owner:self
userInfo:nil];
// Add it
[self addTrackingArea:self.trackingArea];
}
- (void)mouseEntered:(NSEvent *)theEvent {
// TODO: Change text field into a plus sign.
}
- (void)mouseExited:(NSEvent *)theEvent {
// TODO: Change text field back into a regular text field.
}
@end
After creating your subclass, go into Interface Builder, select your NSTextField and change the class to the subclass you created.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments