Objective-C 中的鼠标按下事件
我知道这个问题以前已经被问过很多次了,但对我来说没有任何作用。下面的代码根本不会做任何事情。
- (void) mouseDown:(NSEvent*)event {
NSLog(@"It worked!");
}
我尝试了很多不同的方法来让它工作,包括以这种方式创建自定义 NSEvents:
NSEvent *someEvent;
- (void) mouseDown:(NSEvent*)someEvent {
NSLog(@"It worked!");
}
这是我的 .h 文件:
@interface test : NSWindow <NSWindowDelegate> {
}
有人会解释如何让它做某事吗?
I know this question has been asked a lot before, but nothing will work for me. The following code will not do anything at all.
- (void) mouseDown:(NSEvent*)event {
NSLog(@"It worked!");
}
I have tried a lot of different methods to get this to work, including creating custom NSEvents
in this way:
NSEvent *someEvent;
- (void) mouseDown:(NSEvent*)someEvent {
NSLog(@"It worked!");
}
This is my .h file:
@interface test : NSWindow <NSWindowDelegate> {
}
Would somebody explain how to make this do something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
确保您的类继承自
NSWindow
并符合
协议。否则,这只是一个名为mouseDown
的方法,没有人会调用它。更新:更改头文件,使其如下所示:
换句话说,不要将
mouseDown
原型放入接口定义中,或.h
文件中的任何其他位置。在您的实现文件 (
.m
) 中仅放置以下方法:假设您已在设备中打开日志记录(您确定可以从设备中的其他位置读取
NSLog
输出吗?程序?),您应该看到“它成功了!”印在那里。无论如何,我都不是 obj-C 专家,但我认为通过将 mouseDown 原型放入接口定义中,您基本上是在创建自己的自定义 mouseDown 方法,该方法隐藏了“真正的”。这向编译器表明,它不应该在单击窗口时调用
mouseDown
方法。Make sure your class inherits from
NSWindow
and conforms to the<NSWindowDelegate>
protocol. Otherwise, that's just a method that happens to be namedmouseDown
, and nobody will ever call it.Update: Change your header file so that it looks like this:
In other words, don't put a prototype of
mouseDown
inside the interface definition, or anywhere else in the.h
file.In your implementation file (
.m
) put just the method:Assuming that you have logging turned on in the device (are you sure you can read
NSLog
output from elsewhere in your program?), you should see "It worked!" printed there.I'm not an obj-C expert by any means, but I think by putting the
mouseDown
prototype inside the interface definition, you were basically creating your own custommouseDown
method which hid the "real" one. This indicated to the compiler that it should not call yourmouseDown
method on a window click.你的子类必须有一个NSResponder的父类,否则你不会得到任何事件。
Your subclass must have a parent class of NSResponder, otherwise you will not get any events.
您要重写 NSWindow 类,您应该重写 NSWindow 类的 NSView“contentView”来捕获鼠标事件。 contentView 之外的窗口上的大多数装饰(NSView)都是私有的。
只需创建一个新的 NSView 来覆盖 mouseDown 等,并将其作为内容视图添加到 NSWindow 对象中。
You're overriding the NSWindow class, you should be overriding the NSView "contentView" of the NSWindow class to capture mouse events. Most of the decorations (NSViews) on the window outside of the contentView are private.
Just create a new NSView that overrides mouseDown, etc and add it as your content view to the NSWindow object.