Rainbow text in TextView, iOS and OSX

匆匆过客 提交于 2019-12-03 21:08:34

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:

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