彩虹文本在TextView,iOS和OSX [英] Rainbow text in TextView, iOS and OSX

查看:133
本文介绍了彩虹文本在TextView,iOS和OSX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为应用程式加入一些不同的文字颜色,以便与图片融合。我有很多输入,我的用户想要彩虹文本颜色和重复。因此,例如: stackoverflow 看起来像这样: s = red t = orange a = yellow c = green k = blue o = purple v =粉红色e =红色r =橙色f =黄色l =绿色o =蓝色w =紫色



我如何可以在一个单一的 UITextView
有人知道如何可以实现这个用户正在输入?提示?示例?



我没有看到有关SO彩虹文本的任何其他帖子。

你可以使用 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 blueColor],
[color blueColor],
[color purpleColor],
[color magentaColor]

NSMutableAttributedString * attribString = [[NSMutableAttributedString allocate] initWithString:string];

for(NSInteger location = 0; location< string.length; location ++){
NSRange range = NSMakeRange(location,1);
颜色* color = colors [location%colors.count];
[attribString addAttribute:NSForegroundColorAttributeName value:color range:range];
}
return attribString;
}

输出:



>


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)

解决方案

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:

这篇关于彩虹文本在TextView,iOS和OSX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆