2

私は 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 コーディングの初心者です)、教えてください。

4

3 に答える 3

4

登録するNSWindowDidResignKeyNotificationNSWindowDidResignMainNotification、ウィンドウがフォーカスを失った場合に通知を受け取ります。

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    SEL theSelector = @selector(closeWindow); 
    NSNotificationCenter* theCenter = [NSNotificationCenter defaultCenter]; 
    NSWindow* theWindow = [self window]; 
    [theCenter addObserver:self selector:theSelector name:NSWindowDidResignKeyNotification object:theWindow]; 
    [theCenter addObserver:self selector:theSelector name:NSWindowDidResignMainNotification object:theWindow]; 
}

これで、ウィンドウがフォーカスを失った場合に備えて、以下が実行されます。

-(void)closeWindow
{
    [[self window] close];
}

NSPanelまたは、フォーカスが失われた場合に自動的に非表示になるを使用します。

于 2012-08-18T16:31:20.667 に答える