Search code examples
iphoneiosnsstringnsrange

how to get the NSRange of String highlighted


I am using this code to get the string when tapped in a TextView. I got the strings between . but I need to highlight the tapped string like selection in the copy-paste function in iOS.

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [NSTimer scheduledTimerWithTimeInterval:0.001 target:maintextview   selector:@selector(resignFirstResponder) userInfo:nil repeats:NO];
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    NSRange selectedRange = [textView selectedRange];
    NSString *backString = [maintextview.text substringToIndex:selectedRange.location];
    NSRange backRange = [backString rangeOfString:@"." options:NSBackwardsSearch];
    NSString *forwardString  = [maintextview.text substringFromIndex:backRange.location];
    NSLog(@"%@",[[forwardString componentsSeparatedByString:@"."] objectAtIndex:1]);
 }

How can I get the forwardString highlighted with some colors, when I tap it?


Solution

  • Can't you just generate an NSRange for the forwardString (by using substringFromIndex instead of substringToIndex) and call:

    [textView setSelectedRange];
    

    ?