Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

ios - Perform action by clicking on some word in Uitextview or UILabel

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 heard about NSAttributedString but I'm not sure how to make this with it.

What I want to have is the same results as the facebook app. When you click on a name it push another controller :

facebook example

If you can give me some hint, tutorial or whatever you want please.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...