You can do using NSAttributedString
:
To make it a general method to support OSX and iOS. Now no need to change NSColor
to UIColor
, use this on both the operating systems.
#if TARGET_OS_IPHONE
typedef UIColor Color;
#elif TARGET_OS_MAC
typedef NSColor Color;
#endif
-(NSAttributedString *)colorfulStringFrom:(NSString *)string{
NSArray *colors = @[[Color redColor],
[Color yellowColor],
[Color greenColor],
[Color blueColor],
[Color purpleColor],
[Color magentaColor]
];
NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:string];
for (NSInteger location=0; location<string.length; location++) {
NSRange range = NSMakeRange(location, 1);
Color *color = colors[location%colors.count];
[attribString addAttribute:NSForegroundColorAttributeName value:color range:range];
}
return attribString;
}
Output: