Question

I was replacing some old UIWebViews with UILabels and I realized that I had a string that looked like the following :

NSString * eaten = YOU ATE <b>%@</b> FROM %.

This sentence was being called in the following way :

NSString *warning = [NSString stringWithFormat:eaten, "CAKE", "JANINE"];

This was displayed as :

YOU ATE
CAKE
FROM JANINE.

Which is how I want it to be displayed. How do I now add the line break for the NSString though?

I've tried the following and they all did not work :

NSString *warning = [NSString stringWithFormat:@"%@\r%@\r%@",eaten, "CAKE", "JANINE"];
NSString *warning = [NSString stringWithFormat:@"%@\n%@\n%@",eaten, "CAKE", "JANINE"];
NSString *warning = [NSString stringWithFormat:@"%@\r\n%@\r\n%@",eaten, "CAKE", "JANINE"];

and

self.warningLabel.numberOfLines = 0;

But the output comes off as :

You sent %@ to %@.

What do I do here?

Was it helpful?

Solution

You need to either change the eaten string directly (easiest and cleanest) or add newlines around the middle one

NSString *warning = [NSString stringWithFormat:eaten, @"\nCAKE\n", @"JANINE"];

If it's a variable you'll need to use [NSString stringWithFormat:@"\n%@\n", middleVar] to construct it.

Either way, it's a bad idea to get a format from a variable like that. Use a literal directly so the compiler can check the argument numbers and types for you.

OTHER TIPS

Try this:

[NSString stringWithFormat:@"YOU ATE\n%@\nFROM %@.", "CAKE", "JANINE"];

If you want to reuse format:

NSString *eaten = @"YOU ATE\n%@\nFROM %@.";
[NSString stringWithFormat:eaten, "CAKE", "JANINE"];

Use backslashes \n instead of forward slashes /n.

NSString *warning = [NSString stringWithFormat:@"%@\n%@\n%@",eaten, "CAKE", "JANINE"];

Update

Oh, you have two format strings. That's no good.

NSString *eaten2 = @"YOU ATE\n%@\nFROM %@.";
NSString *warning = [NSString stringWithFormat:eaten2, "CAKE", "JANINE"];

Don't forget to make your label's height tall enough for the three lines and set numberOfLines to 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top