Search code examples
objective-cmacoscocoansattributedstring

Rainbow text in TextView, iOS and OSX


I'm trying to add some different text colors to my app to be fused to an image. I've got alot of input that my users would like a rainbow text color and repeat. So for instance the word: stackoverflow would look like this: s=red t=orange a=yellow c=green k=blue o=purple v=pink e=red r=orange f=yellow l=green o=blue w=purple

I can't even begin to think how I can do this in one single UITextView Does anyone know how I could achieve this as the user is typing? Tips? Example?

I didn't see any other posts on SO regarding rainbow text for iOS. (correct me if im wrong)


Solution

  • 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:

    enter image description here