将NSTextView坐标转换为屏幕坐标

时间:2012-06-19 08:16:47

标签: cocoa nstextview nspopover

在我的应用程序中,我想在NSTextView中显示popover,需要将NSTextView中所选rect的坐标转换为屏幕坐标。我试过这段代码:

NSWindow* viewWindow = [self window];
NSRect rect = [self firstRectForCharacterRange:[self selectedRange]];
rect = [[self superview] convertRect:rect toView:nil]; //converting to NSClipView coordinate system
rect = [viewWindow convertRectToScreen:rect];
return rect;

它的效果差不多,但是返回的rect的“x”来源极其“破碎”。例如,如果rect.origin.x在开头是670,那么它等于1022。

有什么想法吗?

感谢。

1 个答案:

答案 0 :(得分:4)

我明白了。

- (NSRect)rectForPopover
{    
    NSRect rect = [self firstRectForCharacterRange:[self selectedRange]];
    NSRect txtViewBounds = [self convertRectToBacking:[self bounds]];
    txtViewBounds = [self.window convertRectToScreen:txtViewBounds];

    rect = [[self superview] convertRect:rect toView:nil];
    rect = [self.window convertRectToScreen:rect];

    rect.origin = NSMakePoint(rect.origin.x - txtViewBounds.origin.x - self.window.frame.origin.x, rect.origin.y);

    return rect;
}