0

Is there a way I can assign UIColor to NSString like in

cell.textLabel.text = [UIColor grayColor];

I am trying to add color for following string like :

NSString *text = @"Hello"
[text setColor:[UIColor grayColor]; // It gives error here saying it cannot assign

Is there any other way I can assign color to NSString ?

lifemoveson
  • 1,661
  • 8
  • 28
  • 55

4 Answers4

7

NSString is just a string of characters. It doesn't have a color, font, weight, size, style or anything — just characters. You'll want to use NSAttributedString instead.

But bear in mind that NSAttributedString isn't an NSString — it's basically a lightweight container that pairs a string with a dictionary of attributes and provides appropriate drawing code. In particular, you can't pass an NSAttributedString to an API that expects a string. You either have to have an API that takes an NSAttributedString or be drawing the string yourself.

Community
  • 1
  • 1
Chuck
  • 234,037
  • 30
  • 302
  • 389
  • NSForegroundColorAttributeName is undeclared. Can we use it ? – lifemoveson Oct 13 '11 at 21:34
  • 1
    @lifemoveson: You'll want to use the Core Text equivalent, `kCTForegroundColorAttributeName`. As noted in the iOS NSAttributedString docs, it's mainly used with Core Text. – Chuck Oct 13 '11 at 21:37
1

You can't assign a color to a string. A string doesn't have data about color. You can assign a color to a label, like

cell.textLabel.textColor = [UIColor grayColor];

You have to wait until you display the string to set the color. If you need to, you can store the color in a variable of type UIColor * until later.

morningstar
  • 8,952
  • 6
  • 31
  • 42
0

You don't set the color on the string, you set it on the label. The string is just a sequence of characters - the label is responsible for displaying it and so controls things like color.

Take a look at UILabel class reference and look for the textColor property.

In your example, I think you want:

cell.textLabel.textColor = [UIColor grayColor];
triangle_man
  • 1,072
  • 6
  • 10
0

https://github.com/AliSoftware/OHAttributedLabel

1.Above is a link 4 files from github which u download and place it in your project folder.

2.Then #import "NSAttributedString+Attributes.h" in you .m file.

3.Now u can change your string color, font, size etc. like below.

NSString *prev = @"Name: ";

NSMutableAttributedString *now = [NSMutableAttributedString  attributedStringWithString:prev];

[now setTextColor:[UIColor blueColor]];

[now setFont:[UIFont fontWithName:@"AppleGothic" size:24]];
Himanshu Mohan
  • 722
  • 9
  • 30