突出显示在iOS中搜索文本

时间:2014-08-04 09:21:35

标签: ios objective-c uitextview

我有gridview包含TextView。还有一个搜索栏。当我输入要搜索的内容时,搜索文本应在TextView中与Xcode或浏览器相同。

如何实现此功能?

3 个答案:

答案 0 :(得分:8)

我测试了以下代码,它突出显示了UITextView中的特定字符串:

-(void) highlightText:(NSString *)srcTxt {
    int srcTxtLen = srcTxt.length;
    int idx = 0;
    while (idx<(self.txtView.text.length-srcTxtLen)) {
        NSRange srcRange = NSMakeRange(idx, srcTxtLen);
        if ([[self.txtView.text substringWithRange:srcRange] isEqualToString:srcTxt]) {
            NSMutableAttributedString *tmpAttrTxt = [[NSMutableAttributedString alloc] initWithAttributedString:self.txtView.attributedText];
            [tmpAttrTxt addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:srcRange];
            self.txtView.attributedText = tmpAttrTxt;
            idx += srcTxtLen;
        } else {
            idx++;
        }
    }
}

希望它对你有所帮助。当然,它可以根据您的特定需求进行优化和/或定制。

答案 1 :(得分:0)

根据我对您的问题的理解,您需要使用功能突出显示与您在搜索栏中输入的文本相匹配的文本(在textview中,在gridview中)。在这种情况下,您可以尝试以下方法:

  1. 为您的搜索栏实施- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text方法。

  2. 对网格中的文本使用属性文本。 (从xib中的纯文本更改为属性文本)

  3. 每次程序进入上述方法时,都会提取文本变量,并相应地使用适当的属性字符串更新所有textView。为此,您可以使用以下内容:

    NSRange highLightAt = NSMakeRange(17,2);  //based on the text in search bar
    
    NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"You searched for me !!!"];
    
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:highLightAt];
    
    self.textView.attributedText = string;
    
  4. 我希望你明白这一点。

答案 2 :(得分:0)

@ nsz的回答是正确的。但它可能效率不高。因为您无法假设用户将如何搜索文本。示例:如果原始文本是&#34; iPhone已发布新的8s&#34;搜索文本是&#34; iphone 8&#34;,在这种情况下@ nsz的答案不会起作用。要处理这种情况,您必须拆分关键字并找到单词distance,因为&#39; 8&#39;和&#39; 8s&#39;不一样。 要查找单词距离,可以使用Levenshtein算法。下面是实现:

-(float)LevenshteinAlgo:(NSString *)mainString withString:(NSString *)wordToCompare
{
    [mainString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [wordToCompare stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

mainString = [mainString lowercaseString];
wordToCompare = [wordToCompare lowercaseString];

NSInteger k, i, j, cost, * d, distance;

NSInteger n = [mainString length];
NSInteger m = [wordToCompare length];

if( n++ != 0 && m++ != 0 ) {

    d = malloc( sizeof(NSInteger) * m * n );


    for( k = 0; k < n; k++)
        d[k] = k;

    for( k = 0; k < m; k++)
        d[ k * n ] = k;


    for( i = 1; i < n; i++ )
        for( j = 1; j < m; j++ ) {


            if( [mainString characterAtIndex: i-1] ==
               [wordToCompare characterAtIndex: j-1] )
                cost = 0;
            else
                cost = 1;


            d[ j * n + i ] = [self CstyleMinimum: d [ (j - 1) * n + i ] + 1
                                           andOf: d[ j * n + i - 1 ] +  1
                                           andOf: d[ (j - 1) * n + i - 1 ] + cost ];


            if( i>1 && j>1 && [mainString characterAtIndex: i-1] ==
               [wordToCompare characterAtIndex: j-2] &&
               [mainString characterAtIndex: i-2] ==
               [wordToCompare characterAtIndex: j-1] )
            {
                d[ j * n + i] = [self CstyleMinimum: d[ j * n + i ]
                                              andOf: d[ (j - 2) * n + i - 2 ] + cost ];
            }
        }

    distance = d[ n * m - 1 ];

    free( d );

    return distance;
}
return 0.0;
}

-(NSInteger)CstyleMinimum:(NSInteger)a andOf:(NSInteger)b andOf:(NSInteger)c
{
    NSInteger min = a;
    if ( b < min )
        min = b;

if( c < min )
    min = c;

return min;
}

-(NSInteger)CstyleMinimum:(NSInteger)a andOf:(NSInteger)b
{
    NSInteger min=a;
    if (b < min)
        min=b;

    return min;
}

所以整个过程如下:

-(NSString*)getSuggestedString:(NSString *)main key:(NSString *)keyword{
NSString *suggested = nil;
NSArray *split = [main componentsSeparatedByString:@" "];
for (NSString *str in split){
    float distance = floorf([self LevenshteinAlgo:str withString:keyword]);

    if(distance == 1 || distance == 2){
        suggested = str;
    }
}
return suggested;
}

-(void)setColorForText:(NSString*) textToFind withColor:(UIColor*) color
{
    NSRange range = [self.mutableString rangeOfString:textToFind options:NSCaseInsensitiveSearch];

    if (range.location == NSNotFound) {
        //TODO: apply algo
        NSString *suggested = [self getSuggestedString:self.mutableString key:textToFind];
        NSRange srange = [self.mutableString rangeOfString:suggested!=nil?suggested:textToFind options:NSCaseInsensitiveSearch];
        if(srange.location != NSNotFound){
            [self addAttribute:NSForegroundColorAttributeName value:color range:srange];
        }
    }else{
        [self addAttribute:NSForegroundColorAttributeName value:color range:range];
    }
}

NSMutableAttributedString子类中使用此完整代码。将以下代码粘贴到subclass.h文件中。

@interface NSMutableAttributedString (Color){

}
-(void)setColorForText:(NSString*) textToFind withColor:(UIColor*) color;
@end

最后使用如下:

NSMutableAttributedString *bold = [[NSMutableAttributedString alloc]initWithString:fulltext];
[bold setColorForText:key withColor:[UIColor redColor]];

我在我的应用程序中使用了很长时间。你可以尝试