Detect Character Tapped in UITextView

时光毁灭记忆、已成空白 提交于 2019-12-18 18:07:50

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/18704692/detect-character-tapped-in-uitextview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!