4

I've been searching high and low and can't figure out how to do this. Lets say I have a string like this:

NSString *string = @"&foo !foo";

What I'm trying to do is differentiate between the two foos (sounds funny haha) inside a text view. When I click on one, I want to know which (& or !) comes before it. Here's how I'm getting the word:

UITapGestureRecognizer *recognizer = (UITapGestureRecognizer *)sender;
UITextView *TV = (UITextView*)recognizer.view;
CGPoint location = [recognizer locationInView:TV];
location.y += TV.contentOffset.y;
UITextPosition *tapPosition = [TV closestPositionToPoint:CGPointMake(location.x, location.y)];
UITextRange *textRange = [TV.tokenizer rangeEnclosingPosition:tapPosition 
    withGranularity:UITextGranularityWord inDirection:UITextLayoutDirectionRight];
NSString *tappedWord = [TV textInRange:textRange];

I can't figure out how to get the previous character. TV.tokenizer UITextGranularityCharacter only gets the closest letter, not the symbol. Any solutions for this?

Larme
  • 24,190
  • 6
  • 51
  • 81
denikov
  • 877
  • 2
  • 17
  • 35

1 Answers1

5

Check: Convert selectedTextRange UITextRange to NSRange to convert your UITextRange to a NSRange (that I'll call selectedRange).

Inspiring me with the previous answer to the linked question, you'd need to add this at the end of your code:

UITextPosition *beginning = TV.beginningOfDocument;
UITextPosition *selectionStart = textRange.start;
UITextPosition *selectionEnd = textRange.end;
NSInteger location = [TV offsetFromPosition:beginning toPosition:selectionStart];
NSInteger length = [TV offsetFromPosition:selectionStart toPosition:selectionEnd];
NSRange selectedRange = NSMakeRange(location,lenght);
NSRange range = NSMakeRange(selectedRange.location-1,1) //Maybe need to check if selectedRange.location>0
NSString *yourCharString = [[TV text] substringWithRange:range];
Community
  • 1
  • 1
Larme
  • 24,190
  • 6
  • 51
  • 81
  • Thanks for the reply. I saw that post before. Before I make the new NSRange, I have to convert my UITextRange into a NSRange? – denikov May 12 '14 at 11:47
  • 1
    Yes, you have to transform the `UITextRange` (I corrected the "NSTextRange") into a `NSRange`. – Larme May 12 '14 at 11:50
  • Ok thanks. Even though I'm still confused about how to do it. I have the position of the tap, do I still need to break it down to UITextPosition selectionStart and selectionEnd? – denikov May 12 '14 at 11:58
  • 1
    I edited my answer. You should just have to add my code at the end of yours. – Larme May 12 '14 at 12:03
  • Sorry that I made you post the entire answer :) Thanks again. Just didn't know how to modify to fit my example – denikov May 12 '14 at 12:11
  • 1
    It's ok. I just had to paste the previous answer code a rename a few var. But as long as you understand and it works. – Larme May 12 '14 at 12:13