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?
Check: Convert selectedTextRange UITextRange to NSRange to convert your
UITextRange
to aNSRange
(that I'll callselectedRange
).Inspiring me with the previous answer to the linked question, you'd need to add this at the end of your code: