Perform action by clicking on some word in Uitextview or UILabel

后端 未结 3 1119
清歌不尽
清歌不尽 2020-12-06 03:58

How can I do to perform some specific action (like showing a modal or pushing a controller) when user click on some formated/specific word in Uitextview (or UIlabel) ? I\'ve

3条回答
  •  清歌不尽
    2020-12-06 04:26

    Add gesture recognizer to your UITextView:

    //bind gesture
    [_yourTextView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:delegate action:@selector(didReceiveGestureOnText:)]];
    

    And then just check which word is clicked in didReceiveGestureOnText with following code:

    +(NSString*)getPressedWordWithRecognizer:(UIGestureRecognizer*)recognizer
    {
        //get view
        UITextView *textView = (UITextView *)recognizer.view;
        //get location
        CGPoint location = [recognizer locationInView:textView];
        UITextPosition *tapPosition = [textView closestPositionToPoint:location];
        UITextRange *textRange = [textView.tokenizer rangeEnclosingPosition:tapPosition withGranularity:UITextGranularityWord inDirection:UITextLayoutDirectionRight];
    
        //return string
        return [textView textInRange:textRange];
    }
    

    EDIT

    This is how your didReceiveGestureOnText method should look-like:

    -(void)didReceiveGestureOnText:(UITapGestureRecognizer*)recognizer
    {
        //check if this is actual user
        NSString* pressedWord = [delegate getPressedWordWithRecognizer:recognizer];
    }
    

    However this will led you in checking strings after all which is in really cool(as it's slow).

提交回复
热议问题