Using a NSString to set a color for a label

旧城冷巷雨未停 提交于 2019-12-21 20:16:31

问题


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;
}

回答1:


Use this method

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

Call as

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

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"];


来源:https://stackoverflow.com/questions/15456299/using-a-nsstring-to-set-a-color-for-a-label

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!