3

我正在使用下面的代码来检测在 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];
}
4

1 回答 1

4

这段代码在 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);
    }
于 2013-12-18T17:34:09.770 回答