What is the best way to get window coordinates of the current caret posi开发者_StackOverflow中文版tion in a text edit control in Cocoa?
Here is how I do that in other platforms
- Windows -
EM_POSFROMCHAR
- GTK - Using
gtk_text_view_get_iter_location
andgtk_text_view_buffer_to_window_coords
.
I am wondering how the same can be done using Cocoa. I am on MacOSX 10.6.8 and I am doing this using C++.
Assuming textView
is a variable that points to the text view and window
is a variable that points to the 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;
The following method is in the documentation
- (void)drawInsertionPointInRect:(NSRect)aRect color:(NSColor *)aColor turnedOn:(BOOL)flag
it says
The focus must be locked on the receiver when this method is invoked. You should not need to invoke this method directly.
If you override this method (and call the super implementation) in an NSTextView subclass it would allow you to know the position of the insertion point, at least when it's required by Cocoa.
精彩评论