我应该如何在 Cocoa 窗口控制器中获取鼠标事件,或者我应该尝试另一种方式?
我正在设计一个功能,当鼠标悬停在其区域上时,文本字段会变成一个大加号。
我应该如何在 Cocoa 窗口控制器中获取鼠标事件,或者我应该尝试另一种方式?
我正在设计一个功能,当鼠标悬停在其区域上时,文本字段会变成一个大加号。
我建议继承 NSTextField 并在那里处理事件。正如 trojanfoe 所说,它内置了鼠标处理功能。此外,您描述的功能听起来像是您可能会在同一个应用程序或另一个应用程序中再次使用的东西。只需将类设置为您的自定义 NSTextField 即可节省时间。
它可能看起来像这样:
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
创建子类后,进入 Interface Builder,选择 NSTextField 并将类更改为您创建的子类。