【发布时间】:2012-08-18 15:30:52
【问题描述】:
我正在为 Mac 进行编程。我只有很少的 iOS 开发经验。 我需要构建非常简单的应用程序,坐在菜单栏中。 我希望它有点习惯,决定使用 NSWindow 并将其附加到 NSStatusItem。
我的 AppDelegate 是这样的:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
float width = 30.0;
float height = [[NSStatusBar systemStatusBar] thickness];
NSRect viewFrame = NSMakeRect(0, 0, width, height);
statusItem = [[NSStatusItem alloc] init];
statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:30];
[statusItem setView:[[TSStatusBarItem alloc] initWithFrame:viewFrame]];
}
- (void)buttonClicked:(int)posx posy:(int)posy {
[_window setLevel:kCGMaximumWindowLevelKey];
opened = !opened;
NSLog(@"Window is shown: %i", opened);
[_window setFrameTopLeftPoint:NSMakePoint(posx, posy)];
if(opened == YES) {
_window.isVisible = YES;
} else {
_window.isVisible = NO;
}
}
是TSStatusBarItem的代码
- (void)drawRect:(NSRect)rect
{
// Drawing code here.
if (clicked) {
[[NSColor selectedMenuItemColor] set];
NSRectFill(rect);
}
NSImageView *subview = [[NSImageView alloc] initWithFrame:CGRectMake(3, 0, 20, 20)];
[subview setImage:[NSImage imageNamed:@"icon.png"]];
[self addSubview:subview];
}
- (void)mouseDown:(NSEvent *)event
{
NSRect frame = [[self window]frame];
NSPoint pt = NSMakePoint(NSMinX(frame), NSMinY(frame));
NSLog(@"X: %f and Y: %f", pt.x, pt.y);
[self setNeedsDisplay:YES];
clicked = !clicked;
[appDelegate buttonClicked:pt.x posy:pt.y];
}
窗口显示和隐藏得很好,但前提是我点击了 StatusItem。我想添加隐藏窗口的行为,当用户点击外部或在菜单栏中选择另一个项目时(与典型的 NSMenu 应用程序类似)。
怎么做?如果您知道如何简化我的代码(对不起,我是 Mac 编码的新手)- 请说。
【问题讨论】:
-
为什么每次调用draw rect时都添加一个新的图像视图?我建议将那部分代码添加到 init 方法中,或者以编程方式绘制图像。 ;)
-
@TannerSilva - 谢谢!我这样做了。
-
另外,点击状态项时是否会出现 NSMenu?
-
@TannerSilva 不。我只是“打开”NSWindow 并移动到 NSStatusItem 点。
-
好的。我在想你可以让你的 AppDelegate 成为一个 NSMenuDelegate,它会在状态菜单关闭时通知你。
标签: xcode cocoa nswindow nsstatusitem