Search code examples
iosobjective-cuitableviewuisearchbaruisearchdisplaycontroller

in a searchDisplayController 's results, how can I highlight the string typed in in the UISearchBar?


I have a searchDisplayController, I want the results to bold out any occurrences of the string that was typed in the search bar.

enter image description here

in this case, the expected behavior of the search results should have the string "Bla" in the search results highlighted(or changed to a different style - italicized etc)

I've tried looking into NSMutableAttributedString and NSAttributedString, but still a bit unsure of how to change the style of the string in the search results


Solution

  • You can use the following to do what you want. It basically takes your search string and creates a regular expression which will be used to find all occurrences of the search string in the results string. We then loop through these results and change the font attribute to a bold font.

    NSString *searchText = @"searc";
    
    NSString *resultsText = @"I want to highlight what I'm searching for in these search results. Searching can often…";
    
    NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:resultsText];
    
    NSString * regexPattern = [NSString stringWithFormat:@"(%@)", searchText];
    
    // We create a case insensitive regex passing in our pattern
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexPattern options:NSRegularExpressionCaseInsensitive error:nil];
    
    NSRange range = NSMakeRange(0,resultsText.length);
    
    [regex enumerateMatchesInString:resultsText
                            options:kNilOptions
                              range:range
                         usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
    
        NSRange subStringRange = [result rangeAtIndex:1];
    
        // Make the range bold
        [mutableAttributedString addAttribute:NSFontAttributeName
                                        value:[UIFont fontWithName:@"Helvetica-Bold" size:15.0]
                                        range:subStringRange];
    }];
    
    // Replace your result string with the updated attributed string
    self.resultLabel.attributedText = mutableAttributedString;
    

    This will give you something like this: enter image description here