检测在UITextView中点击的字符

检测在UITextView中点击的字符

本文介绍了检测在UITextView中点击的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码来检测UITextView中的单词。这工作正常,但我想检测一些特殊字符,如。使用 UITextGranularityWord 时,不会显示为单词的一部分,我似乎无法将其显示为使用 UITextGranularityCharacter 时显示。

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


推荐答案

此代码对我有用iOS 6:

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);
    }

这篇关于检测在UITextView中点击的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 16:50