我的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];
Jason Coco.. 135
问题是你不想打电话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.
您可以让发件人makeKeyAndOrderFront
或orderFront
任何适合您的具体情况.
问题是你不想打电话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.
您可以让发件人makeKeyAndOrderFront
或orderFront
任何适合您的具体情况.
另请注意,如果要在main.m文件中以编程方式实例化没有主nib的应用程序,则可以如下所示实例化AppDelegate.然后在您的应用程序Supporting Files/YourApp.plist 主nib基本文件/ 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; }
尝试
[window makeKeyAndOrderFront:self];
代替
[window display];
那是你的目标吗?