如何以编程方式创建 Cocoa 窗口? [英] How do I create a Cocoa window programmatically?
问题描述
我的 Cocoa 应用程序需要一些动态生成的小窗口.如何在运行时以编程方式创建 Cocoa 窗口?
My Cocoa app needs some small dynamically generated windows. How can I programmatically create Cocoa windows at runtime?
到目前为止,这是我的非工作尝试.我看不到任何结果.
This is my non-working attempt so far. I see no result whatsoever.
NSRect frame = NSMakeRect(0, 0, 200, 200);
NSUInteger styleMask = NSBorderlessWindowMask;
NSRect rect = [NSWindow contentRectForFrameRect:frame styleMask:styleMask];
NSWindow * window = [[NSWindow alloc] initWithContentRect:rect styleMask:styleMask backing: NSBackingStoreRetained defer:false];
[window setBackgroundColor:[NSColor blueColor]];
[window display];
推荐答案
问题是你不想调用display
,你想调用makeKeyAndOrderFront
或 orderFront
取决于您是否希望窗口成为关键窗口.您可能还应该使用 NSBackingStoreBuffered
.
The problem is that you don't want to call display
, you want to call either makeKeyAndOrderFront
or orderFront
depending on whether or not you want the window to become the key window. You should also probably use NSBackingStoreBuffered
.
此代码将在屏幕左下角创建无边框的蓝色窗口:
This code will create your borderless, blue window at the bottom left of the screen:
NSRect frame = NSMakeRect(0, 0, 200, 200);
NSWindow* window = [[[NSWindow alloc] initWithContentRect:frame
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO] autorelease];
[window setBackgroundColor:[NSColor blueColor]];
[window makeKeyAndOrderFront:NSApp];
//Don't forget to assign window to a strong/retaining property!
//Under ARC, not doing so will cause it to disappear immediately;
// without ARC, the window will be leaked.
您可以为 makeKeyAndOrderFront
或 orderFront
设置适合您情况的发送器.
You can make the sender for makeKeyAndOrderFront
or orderFront
whatever is appropriate for your situation.
这篇关于如何以编程方式创建 Cocoa 窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!