Mouse Down events in Objective-C
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 : NSWindo开发者_C百科w <NSWindowDelegate> {
}
Would somebody explain how to make this do something?
Make sure your class inherits from NSWindow
and conforms to the <NSWindowDelegate>
protocol. Otherwise, that's just a method that happens to be named mouseDown
, and nobody will ever call it.
Update: Change your header file so that it looks like this:
@interface test : NSWindow <NSWindowDelegate> {
}
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:
- (void) mouseDown:(NSEvent*)someEvent {
NSLog(@"It worked!");
}
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 custom mouseDown
method which hid the "real" one. This indicated to the compiler that it should not call your mouseDown
method on a window click.
Your subclass must have a parent class of NSResponder, otherwise you will not get any events.
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.
精彩评论