检测在UITextView中点击的字符

时间:2013-09-09 18:36:05

标签: ios uitextview nsrange

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

1 个答案:

答案 0 :(得分:3)

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