3

I'm using the below code to detect words tapped in a UITextView. This works fine, but I want to detect some special characters, like a ?. ? doesn't show up as part of a word when using UITextGranularityWord and I can't seem to get it to show up when using UITextGranularityCharacter either.

How can I detect taps on single special characters such as the ??

-(NSString*)getWordAtPosition:(CGPoint)pos inTextView:(UITextView*)_tv { //eliminate scroll offset pos.y += _tv.contentOffset.y; //get location in text from textposition at point UITextPosition *tapPos = [_tv closestPositionToPoint:pos]; //fetch the word at this position (or nil, if not available) UITextRange * wr = [_tv.tokenizer rangeEnclosingPosition:tapPos withGranularity:UITextGranularityWord inDirection:UITextLayoutDirectionRight]; if ([_tv textInRange:wr].length == 0) {//i.e. it's not a word NSLog(@"is 0 length, check for characters (e.g. ?)"); UITextRange *ch = [_tv.tokenizer rangeEnclosingPosition:tapPos withGranularity:UITextGranularityCharacter inDirection:UITextLayoutDirectionRight]; NSLog(@"ch range: %@ ch text: %@",ch, [_tv textInRange:ch] ); // logs: ch range: (null) ch text: if ([[_tv textInRange:ch] isEqualToString:@"?"]) { return [_tv textInRange:ch]; } } return [_tv textInRange:wr]; } 
6
  • You can try this: stackoverflow.com/questions/5091851/… Commented Sep 9, 2013 at 19:06
  • I'm not sure how that would work - if my function to return the tapped character can't return the ?, how can I use NSCharacterSet? I don't want to check if a ? exists in the string, but only if it exists in the location that the user taps. Commented Sep 12, 2013 at 17:41
  • Ok I misundestood sorry. You want to get the character which is tapped in your textView, right? I tested you code, that works for the "?", you can use the same way to test all the special character? Commented Sep 12, 2013 at 18:31
  • That's really odd - because I can't get it to detect special characters that are part of a word: foo? becomes foo or that are by themselves ?. It just returns an empty NSRange and string. I'm using the GM, perhaps this is a bug? Commented Sep 15, 2013 at 17:58
  • Same problem iOS 7.1.2 :( Commented Jul 9, 2014 at 11:37

1 Answer 1

4

This code worked for me on iOS 6:

 - (void)tappedTextView:(UITapGestureRecognizer *)recognizer { UITextView *textView = (UITextView *)recognizer.view; CGPoint location = [recognizer locationInView:textView]; UITextPosition *tapPosition = [textView closestPositionToPoint:location]; UITextRange *textRange = [textView.tokenizer rangeEnclosingPosition:tapPosition withGranularity:UITextGranularityCharacter inDirection:UITextLayoutDirectionRight]; NSString *character = [textView textInRange:textRange]; NSLog(@"%@", character); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.