繁体   English   中英

在可可窗口控制器中获取鼠标事件

[英]get mouse event in cocoa window controller

我应该如何在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,然后将该类更改为您创建的子类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM