Search code examples
iosuitableviewtouchuitextviewdatadetectortypes

UITextView inside UITableViewCell - touch go through if not clicking on a link


I'm trying to have the advantage of the UITextView with Data Detector Types inside a TableViewCell that is itself clickable.

The only thing is, I need the UITextView's links to be clickable, so userInteractionEnabled = YES, unfortunately this will prevent any touch going through to the UITableViewCell.

Of course the UITextView can't be edited, I also subclassed it refusing it to be first responder to avoid selecting text in it.

The only thing I need, is detecting that if a user touch the UITextView, check if it was a link, if it is then opening the link, otherwise redirect the touch on the UITableViewCell.

any idea how can this be done ?

much like the twitter App (we can either click on the row, or on the link...)


Solution

  • I know that this question has been asked a while ago, but the behaviour is still very much needed for some app to have a clickable Cell with UIDataDetectors.

    So here's the UITextView subclass I made up to fit this particular behaviour in a UITableView

    -(id) initWithFrame:(CGRect)frame {
        self = [super initWithFrame:frame];
        if (self) {
            self.delegate = self;
        }
        return self;
    }
    
    - (BOOL)canBecomeFirstResponder {
        return NO;
    }
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        UIView *obj = self;
    
        do {
            obj = obj.superview;
        } while (![obj isKindOfClass:[UITableViewCell class]]);
        UITableViewCell *cell = (UITableViewCell*)obj;
    
        do {
            obj = obj.superview;
        } while (![obj isKindOfClass:[UITableView class]]);
        UITableView *tableView = (UITableView*)obj;
    
        NSIndexPath *indePath = [tableView indexPathForCell:cell];
        [[tableView delegate] tableView:tableView didSelectRowAtIndexPath:indePath];
    }
    
    - (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
        return YES;
    }
    

    You can modify this to fit your needs...

    Hope it helps someone.