2011-09-26 27 views
2

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

这是我如何做,在其他平台

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

我想知道如何使用可可做同样的事情。我在MacOSX 10.6.8上,我正在使用C++进行此操作。

+0

我会对NSTextView不感兴趣。感谢您查看这个。 –

+0

还有一个问题:你已经将问题标记为C++,但Cocoa主要提供Objective-C API。 Objective-C(或Objective-C++)是一种可行的解决方案还是只对C++感兴趣? – 2011-09-30 02:38:16

+0

任何关于如何解决问题的想法都会很好。我可以解决语言问题。再次感谢。 –

回答

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; 
+1

在C++中?这看起来不像我见过的任何C++。 – Puppy

+1

@Dead请参阅问题中的评论部分。 – 2011-10-04 03:37:49

+0

这是惊人的..感谢很多。 –

1

以下的方法是在文档中

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

它说

重点必须当这个方法被调用时被锁定在接收器上。你不应该直接调用这个方法。

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

+0

在C++中?这看起来不像我见过的任何C++。 – Puppy

+0

如果你想使用Cocoa(这是由Apple提供的Foundation和AppKit框架的组合),那么api就在Obj-C中。如果你查阅NSTextView的文档,它是一个Obj-C接口和Obj-C方法。没有得到解决。 – jbat100