We might face a situation when we need to add action on tapping a particular word from a string on the iPhone screen like a link or a hashtag etc. Now though we can easily add a UITapGestureRecognizer on a UITextView or UILabel, finding the exact tapped word is tricky. Here is how to do this (using UITextView and UILongPressGestureRecognizer) :
 i) Add gesture recognizer to text view
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressResponse:)];
    [textViewDescription addGestureRecognizer:longPress];
 
 ii) Handle gesture recognizer
- (void)longPressResponse:(UILongPressGestureRecognizer *)recognizer {
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        CGPoint location = [recognizer locationInView:textViewDescription];
        NSString *tappedWord = [self wordAtPosition:CGPointMake(location.x, location.y)];
        NSLog(@"tappedWord %@",tappedWord);
    }
}
iii) Get tapped word
- (NSString *)wordAtPosition:(CGPoint)position
{
    //eliminate scroll offset
    position.y += textViewDescription.contentOffset.y;
    //get location in text from textposition at point
    UITextPosition *tapPosition = [textViewDescription closestPositionToPoint:position];
    //fetch the word at this position (or nil, if not available)
    UITextRange *textRange = [textViewDescription.tokenizer rangeEnclosingPosition:tapPosition withGranularity:UITextGranularityWord inDirection:UITextLayoutDirectionRight];
    
    NSString *tappedWord = [[NSString alloc]initWithString:[textViewDescription textInRange:textRange]];
    
    int start = [textViewDescription offsetFromPosition:textViewDescription.beginningOfDocument toPosition:textRange.start];
    if (start>0) {
        char lastChar = [textViewDescription.text characterAtIndex:start-1];
        if (lastChar == '#') {
            tappedWord = [NSString stringWithFormat:@"#%@",tappedWord];
        }
    }
    return tappedWord;
}
                       
                    
0 Comment(s)