skyler
skyler

Reputation: 742

Highlight selected character dynamically in iOS

I want to highlight selected character in iOS, as you an see in iPhone iOS 7 Notes app. When you search for particular text the search character will be highlighted in the result displayed in UITableView.

Example:

"This is my name"

h - should 've blue color

y - should 've red color

The character customisation should be dynamic. I hope I've briefed enough.

Looking for excellent response buddies!

Upvotes: 1

Views: 993

Answers (3)

Rafał Sroka
Rafał Sroka

Reputation: 40030

You can easily achieve this by setting an attributed string to the text label in a UITableViewCell that shows an entry of your search results.

You would need to calculate ranges of the substrings that should be highlighted. You can do it using regular expressions as I wrote in my sample code. This way you can support multiple occurrences of the substring in a string.

Then, when you have the ranges you just apply special attributes and set the cell label's attributedText property.

The code could look like this:

NSString *searchTerm = ...;
NSString *text = @"This is a sample text that is super cool";

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];

NSString *pattern = [NSString stringWithFormat:@"(%@)", searchTerm];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                                                                       options:kNilOptions 
                                                                         error:nil];
NSRange range = NSMakeRange(0, text.length);

[regex enumerateMatchesInString:text 
                        options:kNilOptions 
                          range:range 
                     usingBlock:^(NSTextCheckingResult *result, 
                                         NSMatchingFlags flags, 
                                                    BOOL *stop) 
{
    NSRange subStringRange = [result rangeAtIndex:1];

    [attributedString addAttribute:NSForegroundColorAttributeName 
                             value:[UIColor blueColor] 
                             range:subStringRange];
}];

Then it's easy. You just set the UILabel's attributedText when creating a cell in tableView:cellForRowAtIndexPath: method.

This should point you to the right direction.

Upvotes: 0

Rose
Rose

Reputation: 437

Use NsMutableAttributedString to highlight characters

 NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:display];
 [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange([displayString length], ([details.notificationCount length]+2))];
displayLabel.attributedText     = str;

Upvotes: 0

MrHaze
MrHaze

Reputation: 3996

Try having a look at TextKit

This is a nice website that shows you the basics

I hope I understood your question..

Upvotes: 1

Related Questions