Fry
Fry

Reputation: 6275

Highlight part of text in UILabel

in my application I have a UILabel with a lot of text inside. When the user performs a research I want to highlight the background under the text searched by the user. Here an example from "Preview" in MacOSX.

enter image description here

The user searches silence and this word is highlighted in the text.

Any ideas ? Thanks.

Upvotes: 1

Views: 3864

Answers (3)

Dinesh Raja
Dinesh Raja

Reputation: 8501

Maybe this is an old question. But I think this will help to someone.

To highlight a part of text in UILabel, I have written an open source named HighlightLabel.

You can simply specify the hightlightText and highlightColor to highlight it.

_highlightLabel.text = @"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda.";
_highlightLabel.highlightText = @"Lorem ipsum dolor sit er elit lamet";
_highlightLabel.highlightColor = [UIColor yellowColor];

Upvotes: 1

Jelle De Laender
Jelle De Laender

Reputation: 577

You'll need to enable the 'attributed' text of the UILabel (or UITextView/custom view). Then you'll need to find/make a nice/fast algorithm to change the color (bg/text) color of some parts of the text. You should be able to find quite a lot on 'attributed string' algorithms to mark some words/matches.

Please check also http://iphonedevelopment.blogspot.be/2011/03/attributed-strings-in-ios.html

In case of, it can maybe be easier/quicker to use a webview by making a custom HTML with the matched-words in another color/bg-color. A webview can almost look like a normal label, and offers even the option to use links/images/..., which can improve the user-experiences in some cases

Upvotes: 1

Haris Hussain
Haris Hussain

Reputation: 2581

You'll have to use NSAttributedString for this.

This might also help. It is a subclass of UILabel that draws an NSAttributedString and also provides convenience methods for setting the attributes of an NSAttributedString from UIKit classes.

Once desired letters/Characters are found, highlight that part of UIView or anything you are using there.

Upvotes: 0

Related Questions