Search code examples
iphoneiosuilabeluitapgesturerecognizeruitextinput

Tap Gesture on part of UILabel


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 & UITextFieldconform to UITextInput.h; UILabel does not. Is there a workaround for this ??


Solution

  • You could try https://github.com/mattt/TTTAttributedLabel and add a link to the label. When the link is pressed you get a action, so part of the label click works only thing you have to would be customizing the link part of the label. I tried this in the past and it worked flawlessly but my client was not interested in using a third party component so duplicated this functionality using UIWebView and HTML.