Rainbow Text in TextView, iOS, and OSX

I am trying to add some different text colors to my application so that they merge with the image. I have a lot of input that my users would like the colors of the text of the rainbow and repetition. So, for example, the word: stackoverflowwill 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 start to think how I can do it in one. UITextView Does anyone know how I can achieve this when a user types? Advice? Example?

I have not seen any other SO posts regarding rainbow text for iOS. (correct me if I am wrong)

+2
source share
1 answer

You can use NSAttributedString:

OSX iOS. NSColor UIColor, .

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

:

enter image description here

+7

Source: https://habr.com/ru/post/1533898/


All Articles