Mold Boy
Mold Boy

Reputation: 663

Get NSView frame/bounds relative to screen on Mac OS X 10.6

I need to get an NSView's frame/bounds relative to the screen. In other words I need the x and y coordinates to be the position on the screen not the position relative to it's superview.

I've come up with the following solution based on comments.

NSRect frameRelativeToWindow = [self.view
    convertRect:self.view.bounds toView:nil
];
#if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_6
NSPoint pointRelativeToScreen = [self.view.window
    convertRectToScreen:frameRelativeToWindow
].origin;
#else
NSPoint pointRelativeToScreen = [self.view.window
    convertBaseToScreen:frameRelativeToWindow.origin
];
#endif

NSRect frame = self.view.frame;

frame.origin.x = pointRelativeToScreen.x;
frame.origin.y = pointRelativeToScreen.y;

Upvotes: 14

Views: 11117

Answers (1)

omz
omz

Reputation: 53551

NSRect frameRelativeToWindow = [myView convertRect:myView.bounds toView:nil];
NSRect frameRelativeToScreen = [myView.window convertRectToScreen:frameInWindow];

Upvotes: 26

Related Questions