我正在尝试向我的应用程序添加一些不同的文本颜色以融合到图像中。我收到了很多用户想要彩虹文本颜色并重复的输入。例如这个词:stackoverflow
看起来像这样: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
我什至无法开始思考如何在一首单曲中做到这一点UITextView
有谁知道当用户打字时我如何实现这一点?尖端?例子?
我没有看到任何其他关于 iOS 彩虹文本的帖子。 (如我错了请纠正我)
你可以使用NSAttributedString
:
使其成为支持 OSX 和 iOS 的通用方法。现在不需要改变NSColor
to 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;
}
Output:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)