How do you make a UITextView detect link part in the text and still have userInteractionDisabled?

前端 未结 3 953
遇见更好的自我
遇见更好的自我 2020-12-19 03:08

I have a textView that is layered on a tableView cell. I need the user to click on the tableView row to open a viewController but if the textView has a link it must be click

3条回答
  •  鱼传尺愫
    2020-12-19 03:40

    One possible (and complex) solution would be using UIViews with UITapGestureRecogniser inside your UITextView.

    • Firstly, you will need to find the NSRange of your link.

    • Convert NSRange to UITextRange

    • Use code similar to the following to add a UITapGestureRecogniser right on top of the link-text in your UITextView.

      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];
          [tapViewOnText release];
      
          pos = pos2;
      

      }

    What I have done in this code is, got the UITextRange of relevant text, get it's firstRectForRange and added a transparent tap-able UIView right on top of it.

    You would have to get the range of your link using some regEx, convert it to UITextRange, and add tap-able UIViews over them. In case, there might be more than one link in a single textView you might add a tag to each view corresponding to their 'link', and open that link in the target method by checking it's tag.

    NOTE: If your UITextViews are universally un-editable, you might want to try TTTAttributedLabel instead. That is what I do in my UITableViewCells

提交回复
热议问题