سؤال

I need to position my NSWindow in the top right of the screen, just below the menubar (like notifications). What is the best approach for doing this?

هل كانت مفيدة؟

المحلول

You can set the window position to top right corner using:

- (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];
}

Call this method in your applicationDidFinishLaunching:, and also register the windowDidResizeNotification to handle the resize event as:

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

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

}

Now in your notification handler method, again update the window position.

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

نصائح أخرى

Use [NSScreen visibleFrame]:

(untested)

// 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);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top