Ios 检测在UITextView中点击的字符

Ios 检测在UITextView中点击的字符,ios,uitextview,nsrange,Ios,Uitextview,Nsrange,我正在使用下面的代码来检测在UITextView中点击的单词。这很好,但我想检测一些特殊字符,比如??在使用UITextGranularityWord时不会显示为单词的一部分,而且在使用UITextGranularityCharacter时,我似乎也无法让它显示出来 如何检测单个特殊字符(如?)上的点击 -(NSString*)getWordAtPosition:(CGPoint)pos inTextView:(UITextView*)_tv { //eliminate scroll o

我正在使用下面的代码来检测在UITextView中点击的单词。这很好,但我想检测一些特殊字符,比如
<代码>?在使用
UITextGranularityWord
时不会显示为单词的一部分,而且在使用
UITextGranularityCharacter
时,我似乎也无法让它显示出来

如何检测单个特殊字符(如
)上的点击

-(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];
}

这段代码在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);
    }

您可以尝试这样做:我不确定这将如何工作-如果返回点击字符的函数不能返回
,我如何使用
NSCharacterSet
?我不想检查字符串中是否存在
,但只检查它是否存在于用户点击的位置。好的,对不起,我理解错误。您想获取文本视图中点击的字符,对吗?我测试了你的代码,它适用于“?”,你可以用同样的方法测试所有特殊字符?这真的很奇怪-因为我无法让它检测单词中的特殊字符:
foo?
变成
foo
,或者它们本身就是
。它只返回一个空NSRange和字符串。我正在使用GM,可能这是一个bug?与iOS 7.1.2相同的问题:(