0

After trying a lot of different answers from SO, I have decided to ask my own question.

I have a UITableViewCell which contains UITextView. The textview could contain both plain text or links. I basically want the links to be selectable but long pressing on anywhere other than the link should show the menu actions such as copy and paste.

What I have tried so far. I have subclassed UITextView

-(BOOL)canBecomeFirstResponder {
    return NO;
}

I have set bodyTextView.selectable = NO. This does provide the desired effect, but the links become unselectable.

Once I change to bodyTextView.selectable = YES, the links are selectable but longpressing on a textview which has only text in it, selects the text with no actions as shown. enter image description here

Ideally I would want only the links to be selectable. I have also tried

- (void)textViewDidChangeSelection:(UITextView *)textView {
   if(!NSEqualRanges(textView.selectedRange, NSMakeRange(0, 0))) {
       textView.selectedRange = NSMakeRange(0, 0);
   }
}

This definitely removes the selection, but still cannot show the popup action menus. Any help would be appreciated.

Neelesh
  • 3,673
  • 8
  • 47
  • 78

2 Answers2

0

Kindly go through this link for the hyperlink creation and once you create a hyperlink the selectable content based actions would be by default taken care.

UITextView with hyperlink text

Pavan kumar C
  • 393
  • 1
  • 4
  • 15
0

After a lot of tries, I used the following approach. In the subclass of UITextView I checked if user is touching on a link, if not set textview as non selectable

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  UITouch *touch = [[touches allObjects] lastObject];
  CGPoint tapLocation = [touch locationInView:self];
  UITextPosition *textPosition = [self closestPositionToPoint:tapLocation];
  NSDictionary *attributes = [self textStylingAtPosition:textPosition inDirection:UITextStorageDirectionForward];
  NSURL *url = attributes[NSLinkAttributeName];
  if (url) {
      self.selectable = YES;
  }else {
      self.selectable = NO;
  }
  [self.superview touchesBegan:touches withEvent:event];

}

This way if user touches on the non-link portion of the textview, its passed on to the superview.

Neelesh
  • 3,673
  • 8
  • 47
  • 78