views:

42

answers:

2

Hello!

I have a UILabel I created on one of my views in my application. I have it set to a static text in IB, but I'm going to change that text programmatically.

Here's how I was trying to do it.

fahrenheitLabel.text = (@"Temperature: %@", text); 
//fahrenheitLabel is my UILabel
//"text" is a NSString

I expected the output to be Temperature: 84, for example.

No matter what order I try it, however, I always just get 84.

When I do NSLog(@"Temperature: %@", text); I get the desired result in the Console.

Is there any reason why my UILabel is not displaying the same result as the NSLog call?

Thank you for your help!

+2  A: 

Should be:

fahrenheitLabel.text = [NSString stringWithFormat:@"Temperature: %@",text];
Firoze Lafeer
Thanks, that did the trick! Would you be kind enough to give a brief explanation as to why my code didn't work?
willingfamily
Sure. So NSLog() is similar to -[NSString stringWithFormat:]. Both expect a format spec and zero or more additional parameters that are applied to that spec. OTOH, -[UILabel setText:] is something totally different. It expects an NSString and nothing else and does nothing more than copy that string into the label.
Firoze Lafeer
Oh, so it was basically seeing the latter NSString and skipped the first one. Thanks for the help!On a side note, you wouldn't happen to know a simple way to set a certain part of this UILabel to another color would you? :)
willingfamily
No, UILabel won't take an attributed string. So it's all one color, unfortunately.
Firoze Lafeer
Alright, thanks anyway!
willingfamily
+1  A: 

NSLog(,); is a function call that is set up for formatting text and will work. (,); has nothing to do with formating text and won't work.

In fact (,) is just the comma operator. These will be evaluated in order and the last one returned. For example:

int a = 1;
int b = 2;
int c = 3;
int x = a, b, c;

Will leave x with the value of c, that is 3.

In your case the comma operator will just return the last item which is "text" and which is why you see 84 all the time.

You should use the NSString formating calls to combine strings the way that you want.

No one in particular
Thanks for explaining the problem in detail! I understand now. Thanks!
willingfamily