Tap on UITextView and get exact word from text using UITapGestureRecognizer

T

UITapGestureRecognizer is a concrete subclass of UIGestureRecognizer that looks for single or multiple taps. For the gesture to be recognized, the specified number of fingers must tap the view a specified number of times.

Lets see how it work for UITextView.

in .h file add below code
@interface MMExampleRightSideDrawerViewController : MMExampleSideDrawerViewController

in .m file add below code

UITextView *translationLableNew = [[UITextView alloc] initWithFrame:CGRectMake(0, 23, 240, 195 – 23)];
translationLableNew.text = @”WordString pass here”;
translationLableNew.userInteractionEnabled = TRUE;
translationLableNew.delegate = self;
translationLableNew.backgroundColor = [UIColor clearColor];
translationLableNew.editable = FALSE;
translationLableNew.font = [UIFont fontWithName:@”MyriadPro-Light” size:18.0];
[self.view addSubview:translationLableNew];

UITapGestureRecognizer *tapTextView = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapRecognized:)];
tapTextView.delegate = self;
[translationLableNew addGestureRecognizer:tapTextView];

//Add Below Method:

– (void)singleTapRecognized:(UITapGestureRecognizer *)recognizer
{
NSLog(@”Single Tap”);
UITextView *textView_New = (UITextView *)recognizer.view;
CGPoint pos = [recognizer locationInView:textView_New];
NSLog(@”Tap Gesture Coordinates: %.2f %.2f”, pos.x, pos.y);
UITextPosition *tapPos = [textView_New closestPositionToPoint:pos];
UITextRange * wr = [textView_New.tokenizer rangeEnclosingPosition:tapPos withGranularity:UITextGranularityWord inDirection:UITextLayoutDirectionRight];

NSLog(@”WORD: %@”, [textView_New textInRange:wr]);
NSString *selectedText = [textView_New textInRange:wr];
NSLog(@”selectedText: %@”, selectedText);

}

About the author

mayur.bhansali
By mayur.bhansali

Category