0

我对 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;
}
4

1 回答 1

3

首先,不要因为你是初学者而避开 Xcode。作为初学者是使用 Xcode 的众多原因之一。像您所拥有的那样使用完全手动实现的代码是为 OS X 开发应用程序的一种天真的方式,您只会遇到比其价值更多的困难,尤其是对于任何不平凡的事情。

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

于 2013-07-11T03:00:59.683 回答