问题
I'm trying to set the background image of a view based on a passed "artistID." Here is my code so far:
NSString *backgroundImageName = [[NSString alloc]initWithFormat:@"artistbackground%i.png",_artistID];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:backgroundImageName]];
NSLog(@"%@",backgroundImageName);
unfortunately, for the parameter in ImageNamed, I'm passing in: artistibackground1
instead of:
@"artistbackgound1"
Any ideas on how to escape the @ and the quotes??
Thanks!!
回答1:
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:[NSString stringWithFormat:@"@%@",backgroundImageName]];
Essentially make two strings, it will add the @"" in the second.
回答2:
You should use \ before the character you want. An example:
NSLog(@"\@\"Try\"");
The code prints
@"Try"
回答3:
Don't forget that even string constants are NSString objects in Objective-C. This is part of the magic! I frequently see programmers new to the language writing this line:
[NSString stringWithFormat:@"@%@",backgroundImageName];
But you can simplify this line to:
[@"@" stringByAppendingString:backgroundImageName];
Magic!
来源:https://stackoverflow.com/questions/9930053/escaping-the-characters-in-objective-c