可可窗口 - 如何定位在右上角

时间:2013-10-29 15:59:02

标签: objective-c cocoa nswindow

我需要将我的 NSWindow 放置在屏幕的右上角,就在菜单栏下方(如通知)。这样做的最佳方法是什么?

2 个答案:

答案 0 :(得分:10)

您可以使用以下方法将窗口位置设置为右上角:

- (void)setWindowPosition
{
    NSPoint pos;
   pos.x = [[NSScreen mainScreen] visibleFrame].origin.x + [[NSScreen mainScreen] visibleFrame].size.width - [_window frame].size.width ;
    pos.y = [[NSScreen mainScreen] visibleFrame].origin.y + [[NSScreen mainScreen] visibleFrame].size.height - [_window frame].size.height  ;
   [_window setFrameOrigin : pos];
}

applicationDidFinishLaunching:中调用此方法,并注册windowDidResizeNotification以处理resize事件:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [self setWindowPosition];   //set window pos

   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:NSWindowDidResizeNotification object:nil];    //register resize notification

}

现在在您的通知处理程序方法中,再次更新窗口位置。

- (void)handleNotification: (id) sender
{
     [self setWindowPosition];
}

答案 1 :(得分:1)

使用[NSScreen visibleFrame]

(未测试的)

// Assumes self is the NSWindow subclass
NSRect sf = [[NSScreen mainScreen] visibleFrame];
NSRect wf = self.frame;
self.frame = NSMakeRect(NSWidth(sf) - NSWidth(wf), NSHeight(sf) - NSHeight(wf),
                        wf.size.width, wf.size.height);