如何创建GUI并以编程方式响应Cocoa事件?

编程入门 行业动态 更新时间:2024-10-19 18:15:04
本文介绍了如何创建GUI并以编程方式响应Cocoa事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我发现如何以编程方式在Cocoa中创建一个窗口,但无法弄清楚如何对事件做出反应。

I found out how to create a window in Cocoa programmatically but can't figure out how to react to events. The window is not reacting to a Quit request or button click.

我尝试添加以下控制器,并使用setDelegate / setTarget没有运气:

I tried adding the following controller and used setDelegate/setTarget without luck:

@interface AppController : NSObject { } - (IBAction)doSomething:(id)sender; @end @implementation AppController - (IBAction)doSomething:(id)sender; { printf("Button clicked!\n"); } @end int main(int argc, char **args){ NSRect frame = NSMakeRect(0, 0, 200, 200); AppController *controller = [[AppController alloc] init]; > [[NSApplication sharedApplication] setDelegate:controller]; NSWindow* window = [[NSWindow alloc] initWithContentRect:frame styleMask:NSBorderlessWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask backing:NSBackingStoreBuffered defer:NO]; [window setBackgroundColor:[NSColor blueColor]]; NSButton *button = [ [ NSButton alloc ] initWithFrame: NSMakeRect( 30.0, 20.0, 80.0, 50.0 ) ]; [ button setBezelStyle:NSRoundedBezelStyle]; [ button setTitle: @"Click" ]; > [ button setAction:@selector(doSomething:)]; > [ button setTarget:controller]; [ [ window contentView ] addSubview: button ]; [window makeKeyAndOrderFront:NSApp]; [[NSRunLoop currentRunLoop] run]; return 0; }

推荐答案

NSApplication run]而不是 - [[NSRunLoop currentRunLoop] run]。如果你看看方法的基本结构,原因应该很清楚:

You need to invoke -[NSApplication run] instead of -[[NSRunLoop currentRunLoop] run]. The reason should be clear if you look at the basic structure of the method:

- (void)run { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self finishLaunching]; shouldKeepRunning = YES; do { [pool release]; pool = [[NSAutoreleasePool alloc] init]; NSEvent *event = [self nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue:YES]; [self sendEvent:event]; [self updateWindows]; } while (shouldKeepRunning); [pool release]; }

NSApplication封装了很多关于如何获取事件,如何更新窗口。

NSApplication encapsulates a lot about how to get an event, how to dispatch them and how to update windows.

更多推荐

如何创建GUI并以编程方式响应Cocoa事件?

本文发布于:2023-11-24 20:57:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626789.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:并以   事件   方式   GUI   Cocoa

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!