我对 OS X 很陌生,我正在尝试创建一个没有 Xcode 的简单应用程序。我确实发现了一些其他网站这样做,但我无法将事件处理程序附加到我的按钮。
下面是代码(从其他网站制作)。它创建一个窗口和一个按钮,但我不知道如何将该事件附加到按钮:
#import <Cocoa/Cocoa.h>
@interface myclass
-(void)buttonPressed;
@end
@implementation myclass
-(void)buttonPressed {
NSLog(@"Button pressed!");
//Do what You want here...
NSAlert *alert = [[[NSAlert alloc] init] autorelease];
[alert setMessageText:@"Hi there."];
[alert runModal];
}
@end
int main ()
{
[NSAutoreleasePool new];
[NSApplication sharedApplication];
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
id menubar = [[NSMenu new] autorelease];
id appMenuItem = [[NSMenuItem new] autorelease];
[menubar addItem:appMenuItem];
[NSApp setMainMenu:menubar];
id appMenu = [[NSMenu new] autorelease];
id appName = [[NSProcessInfo processInfo] processName];
id quitTitle = [@"Quit " stringByAppendingString:appName];
id quitMenuItem = [[[NSMenuItem alloc] initWithTitle:quitTitle
action:@selector(terminate:) keyEquivalent:@"q"] autorelease];
[appMenu addItem:quitMenuItem];
[appMenuItem setSubmenu:appMenu];
id window = [[[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 200, 200)
styleMask:NSTitledWindowMask backing:NSBackingStoreBuffered defer:NO]
autorelease];
[window cascadeTopLeftFromPoint:NSMakePoint(20,20)];
[window setTitle:appName];
[window makeKeyAndOrderFront:nil];
int x = 10;
int y = 100;
int width = 130;
int height = 40;
NSButton *myButton = [[[NSButton alloc] initWithFrame:NSMakeRect(x, y, width, height)] autorelease];
[[window contentView] addSubview: myButton];
[myButton setTitle: @"Button title!"];
[myButton setButtonType:NSMomentaryLightButton]; //Set what type button You want
[myButton setBezelStyle:NSRoundedBezelStyle]; //Set what style You want
[myButton setAction:@selector(buttonPressed)];
[NSApp activateIgnoringOtherApps:YES];
[NSApp run];
return 0;
}