在TextView中搜索字符串的出现 [英] Search occurrences of a string in a TextView
问题描述
我有一个textview有一个大的文本,我想找到所有出现的字符串(搜索)里面,每次按下搜索滚动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.
感谢
推荐答案
要在文本视图上执行向前搜索,请使用以下代码段 -
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];
}
基本上我们使用 NSString
s rangeOfString:options:range:
方法查找文本,然后使用selectedRange$c $ c>
,并使用 scrollRangeToVisible:
。
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:
.
现在一旦找到,您可以通过修改搜索范围找到下一个匹配项。
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.
}
您也可以通过声明
searchRange = NSMakeRange(0, textRange.location);
,然后传递(NSCaseInsensitiveSearch | NSBackwardsSearch)
在选项
中。
这篇关于在TextView中搜索字符串的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!