BRIT
BRIT

Reputation: 55

Search occurrences of a string in a TextView

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

Upvotes: 3

Views: 3100

Answers (1)

Deepak Danduprolu
Deepak Danduprolu

Reputation: 44633

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.

Upvotes: 7

Related Questions