我想知道如何将UIColor的名称传递给特定的方法?
编辑:
- (id) setLabel:(NSString *)text WithColorName:(NSString *)nameOfColor FontName:(NSString *)f_name FontSize:(float)f_size abel:(UILabel *)templbl
{
templbl.backgroundColor = [UIColor ?????];
return templbl;
}
有什么建议吗?
谢谢..
答案 0 :(得分:14)
NSString *colorStr = @"magenta";
NSString *selectorString = [colorStr stringByAppendingString:@"Color"];
SEL selector = NSSelectorFromString(selectorString);
UIColor *color = [UIColor blackColor];
if ([UIColor respondsToSelector:selector]) {
color = [UIColor performSelector:selector];
}
答案 1 :(得分:1)
- (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;
}
答案 2 :(得分:1)
一个选项是字典,其中名称是键,颜色是值
答案 3 :(得分:1)
您可以动态调用颜色类方法:
- (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;
}
}
答案 4 :(得分:0)
Jhaliya的答案会起作用,实际上并不是你所要求的(在你的例子中你不想传递UIColor
作为参数,你只想传递它的预设字符串名称。
这有点棘手,因为[UIColor redColor]
之类的东西是方法,而不是字符串参数。您必须使用NSSelectorFromString
来实现它。正如Jhaliya的答案所示,更好地传递UIColor。