I could successfully add tap gestures to a part of UITextView with the following code:
UITextPosition *pos = textView.endOfDocument;// textView ~ UITextView
for (int i=0;i<words*2-1;i++){// *2 since UITextGranularityWord considers a whitespace to be a word
UITextPosition *pos2 = [textView.tokenizer positionFromPosition:pos toBoundary:UITextGranularityWord inDirection:UITextLayoutDirectionLeft];
UITextRange *range = [textView textRangeFromPosition:pos toPosition:pos2];
CGRect resultFrame = [textView firstRectForRange:(UITextRange *)range ];
UIView* tapViewOnText = [[UIView alloc] initWithFrame:resultFrame];
[tapViewOnText addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(targetRoutine)]];
tapViewOnText.tag = 125;
[textView addSubview:tapViewOnText];
pos=pos2;
}
I wish to imitate the same behaviour in a UILabel
. The issue is, UITextInputTokenizer
(used to tokenize the individual words) is declared in UITextInput.h
, and only UITextView
& UITextField
conform to UITextInput.h
; UILabel
does not.
Is there a workaround for this ??
Try this. Let your label be label
:
//add gesture recognizer to label
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] init];
[label addGestureRecognizer:singleTap];
//setting a text initially to the label
[label setText:@"hello world i love iphone"];
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self.view];
CGRect rect = label.frame;
CGRect newRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width/2, rect.size.height);
if (CGRectContainsPoint(newRect, touchPoint)) {
NSLog(@"Hello world");
}
}
Clicking on the first half of label will work (It gives log output). Not the other half.