5

I have to get the position on the screen of a string contained in a UITextView. To do that, I tried to get the corresponding UITextPosition(s). The problem is that the UITextView method beginningOfDocument returns nil (same for endOfDocuement). Could someone explain me why? And which solution I could use.

My code looks like this:

- (UITextRange *)getRangeOfString:(NSString *)string inTextView:(UITextView *)tv
{
    UITextPosition *beginning = [tv positionFromPosition:tv.beginningOfDocument offset:[tv.text rangeOfString:string].location];
    UITextPosition *end = [tv positionFromPosition:beginning offset:[tv.text rangeOfString:string].length];

    return ([tv textRangeFromPosition:beginning toPosition:end]);
}
DrummerB
  • 39,814
  • 12
  • 105
  • 142
Aeradriel
  • 1,224
  • 14
  • 36

2 Answers2

8

This is about a month late, but make sure you have the "selectable" property enabled in Interface Builder.

Credit: http://jon-nolen.blogspot.com/2013/10/uitextview-returns-nil-for-uitextinput.html

Gazzini
  • 728
  • 8
  • 19
  • Yeah I found the solution but thanks for your answer. – Aeradriel Feb 07 '14 at 13:13
  • Even after changing the selectable to YES, I am receiving nil from 'UITextInput' methods and properties. Any idea what I might be missing? – pavan309 Mar 01 '15 at 17:01
  • Make sure you linked it correctly in your storyboards file? Confirm, via the debugger, that the UITextView object you're calling the methods on is not nil. Any luck? – Gazzini Mar 02 '15 at 00:49
  • I am not using storyboard, initializing it via code. TextView, TextContainers and layoutManager are not nil. But all the 'UITextInput' Methods and properties are returning nil. I still couldn't figure out the issue. – pavan309 Mar 02 '15 at 07:51
  • Have you set the text? – Gazzini Mar 02 '15 at 14:32
0

Make sure the UITextField is added as a subview of another view. If it exists just in memory, the beginningOfDocument and endOfDocument properties will return nil for some reason.

m1h4
  • 1,139
  • 2
  • 13
  • 22