【问题标题】:Search occurrences of a string in a TextView在 TextView 中搜索字符串的出现
【发布时间】:2011-06-26 03:50:21
【问题描述】:

我有一个带有大文本的 textview,我想在其中找到所有出现的字符串(搜索),每次按搜索时,都会将 textView 滚动到当前出现的范围。

谢谢

【问题讨论】:

    标签: objective-c ios xcode cocoa-touch


    【解决方案1】:

    要对文本视图进行前向搜索,请使用以下 sn-p -

    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];
    }
    

    基本上我们使用NSStrings rangeOfString:options:range: 方法来查找文本,然后使用selectedRange 突出显示文本并使用scrollRangeToVisible: 使其可见。

    现在一旦找到,您可以通过修改搜索范围找到下一个匹配项。

    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);
    

    然后在options 中传递(NSCaseInsensitiveSearch|NSBackwardsSearch)

    【讨论】:

    • 谢谢,我回家试试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 2013-05-06
    • 1970-01-01
    • 2014-02-08
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多