3

I have a textview with a large text, and I would like to find all the occurrences of a string (search) inside it and every time i press search scroll the textView to the range of the current occurrence.

thanks

Deepak Danduprolu
  • 44,595
  • 12
  • 101
  • 105
BRIT
  • 55
  • 2
  • 4

1 Answers1

7

To do a forward search on text view, use the following snippet -

NSRange textRange;
NSRange searchRange = NSMakeRange(0, [textView.text length]);

textRange = [textView.text rangeOfString:searchString 
                                 options:NSCaseInsensitiveSearch 
                                   range:searchRange];

if ( textRange.location == NSNotFound ) {
    // Not there
} else {
    textView.selectedRange = textRange;
    [textView scrollRangeToVisible:textRange];
}

Basically we use the NSStrings rangeOfString:options:range: method to find the text and then highlight the text using selectedRange and make it visible using scrollRangeToVisible:.

Now once found you can find the next occurrence by modifying the search range.

if ( textRange.location + textRange.length <= [textView.text length] ) {
    searchRange.location = textRange.location + textRange.length;
    searchRange.length = [textView.text length] - searchRange.location;

    textRange = [textView.text rangeOfString:searchString 
                                     options:NSCaseInsensitiveSearch 
                                       range:searchRange];

    /* Validate search result & highlight the text */
} else {
    // No more text to search.
}

You can also search backwards by declaring

searchRange = NSMakeRange(0, textRange.location);

and then passing (NSCaseInsensitiveSearch|NSBackwardsSearch) in the options.

Deepak Danduprolu
  • 44,595
  • 12
  • 101
  • 105