简体   繁体   English

在TextView中搜索字符串的出现次数

[英]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. 我有一个带有大文本的textview,我想在其中找到所有出现的字符串(搜索),每次按下搜索时,将textView滚动到当前事件的范围。

thanks 谢谢

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 NSString s rangeOfString:options:range: method to find the text and then highlight the text using selectedRange and make it visible using scrollRangeToVisible: . 基本上我们使用NSStringrangeOfString:options:range:方法来查找文本,然后使用selectedRange突出显示文本,并使用scrollRangeToVisible:使其可见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 . 然后在options传递(NSCaseInsensitiveSearch|NSBackwardsSearch)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM