71

我的 Cocoa 应用程序需要一些小的动态生成的窗口。如何在运行时以编程方式创建 Cocoa 窗口?

到目前为止,这是我的非工作尝试。我看不到任何结果。

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];
4

5 回答 5

147

问题是你不想调用display,你想调用或者调用makeKeyAndOrderFront取决于orderFront你是否希望窗口成为关键窗口。您还应该使用NSBackingStoreBuffered.

此代码将在屏幕左下方创建无边框蓝色窗口:

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.

您可以将发件人设置为适合您的情况makeKeyAndOrderFrontorderFront任何适合您的情况。

于 2008-11-24T14:39:58.063 回答
43

附带说明,如果您想在没有主笔尖的情况下以编程方式实例化应用程序,请在 main.m 文件中/您可以按如下方式实例化 AppDelegate。然后在您的应用程序 Supporting Files / YourApp.plist Main nib base file / MainWindow.xib中删除此条目。然后使用 Jason Coco 的方法在您的 AppDelegates init 方法中附加窗口。

#import "AppDelegate.h":

int main(int argc, char *argv[])
{

  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  [NSApplication sharedApplication];

  AppDelegate *appDelegate = [[AppDelegate alloc] init];
  [NSApp setDelegate:appDelegate];
  [NSApp run];
  [pool release];
  return 0;
}
于 2011-05-12T01:59:24.187 回答
7

尝试

[window makeKeyAndOrderFront:self]; 

代替

[window display];

这就是你的目标吗?

于 2008-11-24T14:39:33.617 回答
3

将评价最高的答案翻译成现代 swift (5) 会给你类似这样的东西:

var mainWindow: NSWindow!

...

mainWindow = NSWindow(
    contentRect: NSMakeRect(0, 0, 200, 200),
    styleMask: [.titled, .resizable, .miniaturizable, .closable],
    backing: .buffered,
    defer: false)
mainWindow.backgroundColor = .blue
mainWindow.makeKeyAndOrderFront(mainWindow)
于 2019-12-02T10:43:40.650 回答
2

这是我自己想出的:

NSRect frame = NSMakeRect(100, 100, 200, 200);
NSUInteger styleMask =    NSBorderlessWindowMask;
NSRect rect = [NSWindow contentRectForFrameRect:frame styleMask:styleMask];
NSWindow * window =  [[NSWindow alloc] initWithContentRect:rect styleMask:styleMask backing: NSBackingStoreBuffered    defer:false];
[window setBackgroundColor:[NSColor blueColor]];
[window makeKeyAndOrderFront: window];

这将显示一个蓝色窗口。我希望这是最佳方法。

于 2008-11-24T14:38:57.860 回答