13

我需要获取 NSView 相对于屏幕的框架/边界。换句话说,我需要 x 和 y 坐标是屏幕上的位置,而不是相对于它的超级视图的位置。

我根据评论提出了以下解决方案。

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;
4

1 回答 1

24
NSRect frameRelativeToWindow = [myView convertRect:myView.bounds toView:nil];
NSRect frameRelativeToScreen = [myView.window convertRectToScreen:frameInWindow];
于 2012-04-24T03:16:58.860 回答