fadd
fadd

Reputation: 584

Coloring a part of NSString Xcode

i am implementing an iOS application, and have two strings concatenated and inserted into a label. I want to give the first string a different color than the second one.

here is my strings and they are concatenated...

NSString *dateVale=[date objectAtIndex:indexPath.row];
NSString *addressValue=[address objectAtIndex:indexPath.row];

TextLabel.text = [NSString stringWithFormat:@"%@ \n%@",dateVale,addressValue];

so how to give the first string a blue color?

Thanks in advance.

Upvotes: 0

Views: 741

Answers (3)

antf
antf

Reputation: 3222

In iOS less than 6.0 your request is not supported unless you use third party classes. Personally I try to avoid third party classes because it happens many times that in future iOS updates some of these third party classes are no more approved by Apple. But I noticed in your output sting that you have each text on a separate line (from the \n):

TextLabel.text = [NSString stringWithFormat:@"%@ \n%@",dateVale,addressValue];

Since you have each one on a line and if you like to avoid using third party classes, you can simply use two UILabels and give each one the formatting you want and in that case you will do:

TextLabel01.text = [NSString stringWithFormat:@"%@", dateVale];
TextLabel02.text = [NSString stringWithFormat:@"%@", addressValue];

By the way even if they were on the same line you can still use 2 separate UILabels and you can play with the frame of each label dynamically by calculating the text width using sizeWithFont.

Upvotes: 1

gimenete
gimenete

Reputation: 2669

The way to go is using NSAttributedStrings. NSAttributedString objects represent strings with associated sets of attributes. Starting with iOS6 UIKit added support for NSAttributedStrings in UILabels and other components.

For previous iOS versions you can use third party components that support NSAttributedStrings such as: OHAttributedLabel, TTTAttributedLabel or Nimbus Attributed Label. These components are implemented using CoreText, a low-level framework for text rendering in iOS. I recommend you using one of these components instead of trying to use CoreText.

You can also use a UIWebView if you need much more complex styling or behaviour, but it's a more heavy-weight approach.

Upvotes: 3

Paresh Navadiya
Paresh Navadiya

Reputation: 38259

Use NSAttributed String. Condition is that u will have to use thirdparty class for attributed Label ie TTTAttributedLabel

EDIT

TTTAttributedLabel is compatible in ios 5.1 version and later.

Note ios6's UILabel support NSAttributedString no need to use thirdparty class label.

Upvotes: 0

Related Questions