有没有办法在 obj-c 中制作一个 gui 窗口,同时没有 .app 包,只是可扩展?问题是我需要一个 gui 应用程序(只有一个对话框)。
我试过: 将 appkit.framework 导入终端应用程序。 - 崩溃有很多原因。 我认为使用 x11 不是一个好主意,因为它不包含在 OS X 10.8 中
那么,有什么想法吗?
最佳答案
遗憾的是,您需要运行一个 NSApplication,但不需要一个应用程序包。
确保在创建项目时选择“Foundation”作为类型。然后你可以这样设置:
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
@interface MyAppDelegate : NSObject <NSApplicationDelegate>
{
NSWindow *window;
}
@end
@implementation MyAppDelegate
-(id) init
{
self = [super init];
if (self)
{
// total *main* screen frame size //
NSRect mainDisplayRect = [[NSScreen mainScreen] frame];
// calculate the window rect to be half the display and be centered //
NSRect windowRect = NSMakeRect(mainDisplayRect.origin.x + (mainDisplayRect.size.width) * 0.25,
mainDisplayRect.origin.y + (mainDisplayRect.size.height) * 0.25,
mainDisplayRect.size.width * 0.5,
mainDisplayRect.size.height * 0.5);
/*
Pick your window style:
NSBorderlessWindowMask
NSTitledWindowMask
NSClosableWindowMask
NSMiniaturizableWindowMask
NSResizableWindowMask
*/
NSUInteger windowStyle = NSTitledWindowMask | NSMiniaturizableWindowMask;
// set the window level to be on top of everything else //
NSInteger windowLevel = NSMainMenuWindowLevel + 1;
// initialize the window and its properties // just examples of properties that can be changed //
window = [[NSWindow alloc] initWithContentRect:windowRect styleMask:windowStyle backing:NSBackingStoreBuffered defer:NO];
[window setLevel:windowLevel];
[window setOpaque:YES];
[window setHasShadow:YES];
[window setPreferredBackingLocation:NSWindowBackingLocationVideoMemory];
[window setHidesOnDeactivate:NO];
[window setBackgroundColor:[NSColor greenColor]];
}
return self;
}
- (void)applicationWillFinishLaunching:(NSNotification *)notification
{
// make the window visible when the app is about to finish launching //
[window makeKeyAndOrderFront:self];
/* do layout and cool stuff here */
}
- (void)applicationDidFinishLaunching:(NSNotification*)aNotification
{
/* initialize your code stuff here */
}
- (void)dealloc
{
// release your window and other stuff //
[window release];
[super dealloc];
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool
{
NSApplication *app = [NSApplication sharedApplication];
[app setDelegate:[[[MyAppDelegate alloc] init] autorelease]];
[app run];
}
return 0;
}
请记住行 [app run];正在阻塞,因此您必须在应用程序循环内或在新线程(首选应用程序循环)上运行您的逻辑。
希望对您有所帮助。
编辑:嘘..我来不及了!
关于Objective-c 如何从终端应用程序制作 GUI 窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15957819/