Reputation: 19418
I want to know that how can I pass UIColor's name to the specific method ?
EDIT :
- (id) setLabel:(NSString *)text WithColorName:(NSString *)nameOfColor FontName:(NSString *)f_name FontSize:(float)f_size abel:(UILabel *)templbl
{
templbl.backgroundColor = [UIColor ?????];
return templbl;
}
any suggestions ?
Thanks..
Upvotes: 3
Views: 3710
Reputation: 45551
You can dynamically invoke the color class methods:
- (id) setLabel:(NSString *)text WithColorName:(NSString *)nameOfColor FontName:(NSString *)f_name FontSize:(float)f_size abel:(UILabel *)templbl
{
SEL colorMethod = NSSelectorFromString([NSString stringWithFormat:@"%@Color", [nameOfColor lowercaseString]]);
// Check if this is a valid color first
if ([[UIColor class] respondsToSelector:colorMethod]) {
// Dynamically invoke the class method
UIColor *color = [[UIColor class] performSelector:colorMethod];
templbl.backgroundColor = color;
}
}
Upvotes: 1
Reputation: 90117
NSString *colorStr = @"magenta";
NSString *selectorString = [colorStr stringByAppendingString:@"Color"];
SEL selector = NSSelectorFromString(selectorString);
UIColor *color = [UIColor blackColor];
if ([UIColor respondsToSelector:selector]) {
color = [UIColor performSelector:selector];
}
Upvotes: 14
Reputation: 31304
Jhaliya's answer will work, it's not actually strictly what you were asking (in your example you don't want to pass a UIColor
as a parameter, you just want to pass it's preset string name.
This is a little tricky, since things like [UIColor redColor]
are methods, not string parameters. You would have to use NSSelectorFromString
to achieve it. Much better to pass a UIColor in as Jhaliya's answer shows.
Upvotes: 0
Reputation: 104698
one option is a dictionary, where the name is the key and the color is the value
Upvotes: 1
Reputation: 31722
- (id) setLabel:(NSString *)text WithColorName:(NSString *)nameOfColor FontName:(NSString *)f_name FontSize:(float)f_size abel:(UILabel *)templbl color:(UIColor*) myLabelColor
{
templbl.backgroundColor = myLabelColor;
return templbl;
}
Upvotes: 1