Rainbow text in TextView, iOS and OSX

北慕城南 提交于 2019-12-21 06:35:01

问题


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)


回答1:


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:



来源:https://stackoverflow.com/questions/22349076/rainbow-text-in-textview-ios-and-osx

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