Color change by tap word in UITextView

74 views
Skip to first unread message

Piyush

unread,
Jul 2, 2014, 9:37:56 AM7/2/14
to byu-coc...@googlegroups.com

Hello,

I want to change color of word when i tap in UITaxview just like in InstaQuote
I write some code
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textTapped:)];
   
    [_textview addGestureRecognizer:tap];


- (void)textTapped:(UITapGestureRecognizer *)recognizer
{
    UITextView *textView = (UITextView *)recognizer.view;
   
    // Location of the tap in text-container coordinates
   
    NSLayoutManager *layoutManager = textView.layoutManager;
    CGPoint location = [recognizer locationInView:textView];
    location.x -= textView.textContainerInset.left;
    location.y -= textView.textContainerInset.top;
   
    NSLog(@"location: %@", NSStringFromCGPoint(location));
    NSLog(@"%@",[self getWordAtPosition:location inTextView:_lbl_test]);

//I got word which i tapped but How to change color of word which I tapped. I have little knowledge of NSMutableAttributedString. but didn't know how? can anyone suggest me what i do?

   
    }


-(NSString*)getWordAtPosition:(CGPoint)pos inTextView:(UITextView*)_tv
{

    pos.y += _tv.contentOffset.y;   
    UITextPosition *tapPos = [_tv closestPositionToPoint:pos];   
    UITextRange * wr = [_tv.tokenizer rangeEnclosingPosition:tapPos withGranularity:UITextGranularityWord inDirection:UITextLayoutDirectionRight];   
    return [_tv textInRange:wr];
}


Joshua Dutton

unread,
Jul 5, 2014, 6:32:13 PM7/5/14
to byu-coc...@googlegroups.com
Disclaimer: I've never done this, but it looks interesting so I looked it up. 

It looks like this code will turn the string in the given range red (you may need NSForegroundColorAttributeName pre iOS7):

[string addAttribute:UITextAttributeTextColor 
               value:[UIColor redColor] 
range:range];
Here are some extra resources I found:

Attributed String Programming Guide:

A nifty label for attributed strings: 

Some stack overflow answers:

--
For our job posting guidelines see http://cocoaheads.byu.edu/newsite/jobPostingGuidelines.html
Be sure to visit our website at http://cocoaheads.byu.edu
---
You received this message because you are subscribed to the Google Groups "BYU CocoaHeads" group.
To unsubscribe from this group and stop receiving emails from it, send an email to byu-cocoahead...@googlegroups.com.
To post to this group, send email to byu-coc...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages