获取插入点的窗口坐标 - Cocoa

Nav*_*K N 2 c++ macos cocoa coordinates

在Cocoa的文本编辑控件中获取当前插入位置的窗口坐标的最佳方法是什么?

以下是我在其他平台上的表现方式

  1. Windows - EM_POSFROMCHAR
  2. GTK - 使用gtk_text_view_get_iter_locationgtk_text_view_buffer_to_window_coords.

我想知道如何使用Cocoa完成同样的工作.我在MacOSX 10.6.8上,我正在使用C++.

小智 5

假设textView是一个指向文本视图window的变量,它是一个指向窗口的变量:

// -firstRectForCharacterRange:actualRange returns a frame rectangle
// containing the insertion point or, in case there's a selection,
// the first line of that selection. The origin of the frame rectangle is
// in screen coordinates
NSRange range = [textView selectedRange];
NSRect screenRect = [textView firstRectForCharacterRange:range actualRange:NULL];

// -convertRectFromScreen: converts from screen coordinates
// to window coordinates
NSRect windowRect = [window convertRectFromScreen:screenRect];

// The origin is the lower left corner of the frame rectangle
// containing the insertion point
NSPoint insertionPoint = windowRect.origin;
Run Code Online (Sandbox Code Playgroud)