UITextView with clickable links but no text highli

2019-02-07 20:32发布

I have a UITextView displaying non-editable text. I want the text to automatically parse links, phone numbers, etc for the user, and for those to be clickable.

I don't want the user to be able to highlight text, though, because I want to override those long press and double-tap interactions to do something different.

In order for links to be parsed in iOS7, the Selectable switch needs to be turned on for the UITextView, but Selectable also enables highlighting, which I don't want.

I tried overriding the LongPress gesture to prevent highlighting, but that seems to have disabled ordinary taps on links as well...

for (UIGestureRecognizer *recognizer in cell.messageTextView.gestureRecognizers) {
    if ([recognizer isKindOfClass:[UILongPressGestureRecognizer class]]){
        recognizer.enabled = NO;
    }
    if ([recognizer isKindOfClass:[UITapGestureRecognizer class]]){
        recognizer.enabled = YES;
    }
}

There are lots of similar threads out there but none seem to address this specific question of links enabled, text not highlightable.

8条回答
叛逆
2楼-- · 2019-02-07 21:17

I'm not sure if this works for your particular case, but I had a similar case where I needed the textview links to be clickable but did not want text selection to occur and I was using the textview to present data in a CollectionViewCell.

I simply had to override -canBecomeFirstResponder and return NO.

@interface MYTextView : UITextView
@end

@implementation MYTextView

- (BOOL)canBecomeFirstResponder {
    return NO;
}

@end
查看更多
Fickle 薄情
3楼-- · 2019-02-07 21:17

Although it's admittedly fragile in the face of possible future implementation changes, Kubík Kašpar's approach is the only one that has worked for me.

But (a) this can be made simpler if you subclass UITextView and (b) if the only interaction you want to allow is link tapping, you can have the tap be recognised straight away:

@interface GMTextView : UITextView
@end

@implementation GMTextView

- (void)addGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer {

  // discard all recognizers but the one that activates links, by just not calling super
  // (in iOS 9.2.3 a short press for links is 0.12s, long press for selection is 0.75s)

  if ([gestureRecognizer isMemberOfClass:UILongPressGestureRecognizer.class] &&
      ((UILongPressGestureRecognizer*)gestureRecognizer).minimumPressDuration < 0.25) {  

    ((UILongPressGestureRecognizer*)gestureRecognizer).minimumPressDuration = 0.0;
    [super addGestureRecognizer:gestureRecognizer]; 
  }
}

@end
查看更多
登录 后发表回答