我對OS X非常陌生,我試圖在沒有Xcode的情況下創建一個簡單的應用程序。我確實發現了其他一些網站,但我無法將事件處理程序附加到我的按鈕上。在沒有Xcode的情況下創建一個OSX應用程序
下面是代碼(從其他網站製作)。它創建一個窗口和一個按鈕,但我不知道如何該事件附加到按鈕:
所有的#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;
}
你爲什麼想這樣做? – Thilo
你的意思是完全一致的(這是一個奇怪的要求)或不使用Interface Builder(這很常見)? – Thilo
如果您是OS X的新手,那麼使用Xcode和Interface Builder是明智的選擇,直到您足夠的知識才能理解它如何在表面下工作。 – dreamlax