gpt4 book ai didi

objective-c - 如何创建 GUI 并以编程方式对 Cocoa 事件使用react?

转载 作者:太空狗 更新时间:2023-10-30 03:28:41 25 4
gpt4 key购买 nike

我找到了如何以编程方式在 Cocoa 中创建窗口,但不知道如何对事件使用react。窗口没有对退出请求或按钮单击使用react。

我尝试添加以下 Controller 并使用 setDelegate/setTarget 但没有成功:

    @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]。如果你看一下方法的基本结构,原因应该很清楚:

- (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 封装了很多关于如何获取事件、如何调度它们以及如何更新窗口的内容。

关于objective-c - 如何创建 GUI 并以编程方式对 Cocoa 事件使用react?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/656129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com