在没有Xcode的情况下创建OSX应用程序

时间:2013-07-11 01:44:07

标签: xcode macos cocoa

我是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;
}

1 个答案:

答案 0 :(得分:2)

首先,不要因为你是初学者而避免使用Xcode。作为初学者是使用Xcode的众多原因之一。使用完全手动实现的代码就像开发OS X应用程序一样天真的方式,你只会遇到比它值得多的困难,特别是对于任何非平凡的事情。

话虽如此,你的按钮没有做任何事情的原因是因为按钮没有目标。所有行动都需要目标。在您的情况下,您想要创建myclass类的实例(请注意,Objective-C中的类名通常以上部camelcase命名,即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!