我在IB中创建了 NSButton 的子类,并将子类设置为我的按钮的自定义类。按钮有效,但在我的主文件( NSObject )中,链接到同一按钮的 someMethod “ IBAction 不起作用。我想做的是点击“if”子类( NSButton ),然后在我的( NSObject )里面,someMethod 退出,好像被点击了一样。但是我 失去了不明白为什么它不会工作,请帮助我,我真的迷路了。
我要给你完整的源代码,我的.h文件中有以下代码:
#import <Cocoa/Cocoa.h>
@interface HoverButton : NSButton
{
NSTrackingArea *trackingArea;
}
- (void)mouseEntered:(NSEvent *)theEvent;
- (void)mouseExited:(NSEvent *)theEvent;
- (void)mouseDown:(NSEvent *)ev;
- (void)mouseUp:(NSEvent *)theEvent;
@end
以下代码为.m文件:
#import "HoverButton.h"
@implementation HoverButton
- (void)updateTrackingAreas
{
[super updateTrackingAreas];
if (trackingArea)
{
[self removeTrackingArea:trackingArea];
[trackingArea release];
}
NSTrackingAreaOptions options = NSTrackingInVisibleRect | NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow;
trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect options:options owner:self userInfo:nil];
[self addTrackingArea:trackingArea];
}
- (void)mouseEntered:(NSEvent *)event
{
[self setImage:[NSImage imageNamed:@"1"]];
}
- (void)mouseExited:(NSEvent *)event
{
[self setImage:[NSImage imageNamed:@"2"]];
}
- (void)mouseDown:(NSEvent *)ev {
[self setImage:[NSImage imageNamed:@"2"]];
}
- (void)mouseUp:(NSEvent *)ev {
[self setImage:[NSImage imageNamed:@"1"]];
}
@end
这是主要的.h文件:
#import <Cocoa/Cocoa.h>
@interface Main : NSObject {
}
-(IBAction) someMethod:(id) sender;
@end
和主.m文件
#import "Main.h"
#import "HoverButton.h"
@implementation Main
-(IBAction) someMethod:(id) sender
{
NSEvent *SKMouseDown; //Mouse down events
HoverButton *frac = [[HoverButton alloc] init];
[frac mouseDown: SKMouseDown];
exit(0); // < --- does not work, someMethod docent work.
}
@end
答案 0 :(得分:1)
如果我理解正确,你想从nsbutton的子类内部的事件中回调父类。 它可以以不同的方式完成:
添加@property(assign)Main * delegate
分配HoverButton后设置frac.delegate = self;
在你想要调用委托调用的任何方法中: if(delegate&amp;&amp; [delegate performSelector:@selector(someMethod :)]){ [委托someMethod:self]; }
这两个平台的所有工作正常