2013-07-11 80 views
0

我對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; 
} 
+3

你爲什麼想這樣做? – Thilo

+3

你的意思是完全一致的(這是一個奇怪的要求)或不使用Interface Builder(這很常見)? – Thilo

+2

如果您是OS X的新手,那麼使用Xcode和Interface Builder是明智的選擇,直到您足夠的知識才能理解它如何在表面下工作。 – dreamlax

回答

2

第一,不迴避的Xcode,因爲你是一個初學者。成爲初學者是使用Xcode的諸多原因之一。採用完全手動實現的代碼,比如你擁有的是一種開發OS X應用程序的天真方式,你只會遇到比它值得的更多的困難,特別是對於任何非平凡的事情。

話雖如此,你的按鈕沒有做任何事情的原因是因爲按鈕沒有目標。所有行動都需要一個目標。在你的情況下,你想創建一個myclass類的實例(注意Objective-C中的類名通常以上層命名,即MyClass)。請注意,您的操作方法也應該有一個參數(即操作的發送者),即使它未被使用。

- (void) buttonPressed:(id) sender 
{ 
    NSLog(@"Button pressed!"); 

    //Do what You want here... 
    NSAlert *alert = [[[NSAlert alloc] init] autorelease]; 
    [alert setMessageText:@"Hi there."]; 
    [alert runModal]; 
} 

// ... 

myclass *mc = [[myclass alloc] init]; 

[myButton setTarget:mc]; 
[myButton setAction:@selector(buttonPressed:)]; 

我不能強調這個代碼有多荒謬。咬緊牙關,潛入Xcode!

+0

dreamlax,非常感謝!這是工作 ! –

相關問題