【问题标题】:Getting window coordinates of the insertion point - Cocoa获取插入点的窗口坐标 - Cocoa
【发布时间】:2018-06-21 01:02:52
【问题描述】:

在 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++ 执行此操作。

【问题讨论】:

  • 我会对 NSTextView 不感兴趣。感谢您对此进行调查。
  • 还有一个问题:您已将问题标记为 c++,但 Cocoa 主要提供了一个 Objective-C API。 Objective-C(或 Objective-C++)是可行的解决方案,还是您只对 C++ 感兴趣?
  • 任何关于如何解决问题的想法都足够了。我可以解决语言问题。再次感谢。

标签: c++ macos cocoa coordinates


【解决方案1】:

假设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;

【讨论】:

  • 在 C++ 中?这看起来不像我见过的任何 C++。
  • @Dead 请参阅问题中的 cmets 部分。
  • 顺便说一句,window 变量是什么? NSWindow 的实例?如果是,我应该传递显示NSTextView 的窗口实例吗?我很困惑,因为这在 MS Windows 和 GTK 中略有不同。在这两者中,每个像文本字段这样的项目实际上都是窗口/小部件的实例。因此,要将屏幕坐标转换为窗口坐标,提供的窗口就是文本字段本身。但是这里的 NsTextView 不是一个窗口。所以我很困惑。你能帮忙吗?
【解决方案2】:

以下方法在文档中

- (void)drawInsertionPointInRect:(NSRect)aRect color:(NSColor *)aColor turnedOn:(BOOL)flag

它说

调用此方法时,焦点必须锁定在接收器上。您应该不需要直接调用此方法。

如果您在 NSTextView 子类中重写此方法(并调用超级实现),它将允许您知道插入点的位置,至少在 Cocoa 需要时。

【讨论】:

  • 在 C++ 中?这看起来不像我见过的任何 C++。
  • 如果你想使用Cocoa(它是Foundation和AppKit框架的组合,苹果提供),api在Obj-C中。如果您查找 NSTextView 的文档,它是一个带有 Obj-C 方法的 Obj-C 接口。没有办法解决这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-20
  • 1970-01-01
  • 2011-03-15
  • 1970-01-01
  • 1970-01-01
  • 2011-12-09
相关资源
最近更新 更多