如何以编程方式创建Cocoa窗口? [英] How do I create a Cocoa window programmatically?

查看:139
本文介绍了如何以编程方式创建Cocoa窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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];


推荐答案

问题是你不想调用 ,您可以根据是否希望窗口成为关键窗口来调用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆