使用NSString为标签设置颜色 [英] Using a NSString to set a color for a label

查看:44
本文介绍了使用NSString为标签设置颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个方法,并使用字符串值"redColor"来设置标签的UIColor.tableColorName是NSString"redColor",我尝试应用选择器来创建UIColor并将其应用于我的textLabel.谢谢

I want to create a method and use a string value "redColor" to set the UIColor for a label. tableColorName is the NSString "redColor" and I tried to apply a selector to create the UIColor and apply it to my textLabel. Thanks

-(void) changeLabelColor
{
    SEL labelColor = NSSelectorFromString([NSString stringWithFormat:[@"%@", tableColorName]]);

    UIColor *color = [[UIColor class] performSelector:labelColor];
    self.textLabel.textColor = color;
}

推荐答案

使用此方法

-(UIColor *)giveColorfromStringColor:(NSString *)colorname
{
    SEL labelColor = NSSelectorFromString(colorname);
    UIColor *color = [UIColor performSelector:labelColor];
    return color;
}

呼叫为

[view setBackgroundColor:[self giveColorfromStringColor:@"redColor"]];

方法名称以 colorname 作为输入,并给出相应的UIColor

The method name takes colorname as input and gives the corresponding UIColor

因此,在您的情况下,通话将会

Thus in your case the call will be

self.textLabel.textColor = [self giveColorfromStringColor:@"redColor"];

这篇关于使用NSString为标签设置颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆