2

I have a UITextField where I am implementing autocomplete in a UIPopoverController. I would like the popover's arrow to point directly at the caret (the way Mail and Messages does in the To: field). How do I get a CGRect that represents the location of the caret?

Note: I am not interested in the position in the text string, which is what this question deals with. I need a way to get the pixel location of the caret relative to the frame of the UITextField.

Community
  • 1
  • 1
i_am_jorf
  • 53,608
  • 15
  • 131
  • 222

1 Answers1

8

Try implementing the below code, it works fine for most of the characters.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    UITextPosition *beginning = textField.beginningOfDocument;
    UITextPosition *start = [textField positionFromPosition:beginning offset:range.location];
    UITextPosition *end = [textField positionFromPosition:start offset:range.length];
    CGRect caretFrame = [textField caretRectForPosition:end];

    return YES;
}
cocoakomali
  • 1,346
  • 1
  • 8
  • 7