Detecting a character in a UITextView
I am using the below code to detect words used in UITextView. This works great, but I want to detect some special characters for example ?
. ?
does not appear as part of a word when used UITextGranularityWord
, and I cannot get it to appear when used UITextGranularityCharacter
.
How can I detect taps for individual special characters like ?
?
-(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 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];
}
+2
source to share
1 answer
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);
}
+3
source to share