你如何使用NSAttributedString? [英] How do you use NSAttributedString?
问题描述
NSString
或 NSMutableStrings
中的多种颜色是不可能的。所以我听说过 NSAttributedString
随 iPad SDK 3.2 (或大约3.2)一起推出并可用iPhone上的 iPhone SDK 4.0测试版。
Multiple colours in an NSString
or NSMutableStrings
are not possible. So I've heard a little about the NSAttributedString
which was introduced with the iPad SDK 3.2 (or around 3.2) and is available on the iPhone as of iPhone SDK 4.0 beta.
我想要一个有三种颜色的字符串。
I would like to have a string that has three colours.
我不使用3个单独的NSStrings的原因是因为三个 NSAttributedString
子串中每个子串的长度经常变化,所以我会更喜欢,不要使用任何计算来重新定位3个单独的 NSString
对象。
The reason I don't use 3 separate NSStrings, is because the length of each of the three NSAttributedString
substrings changes often and so I would prefer, not to use any calculations to re-position 3 separate NSString
objects.
如果可以使用 NSAttributedString
如何进行以下操作 - (如果不能使用NSAttributed字符串,你会怎么做):
If it's possible using NSAttributedString
how do I make the following - (if not possible with NSAttributed string how would you do it):
修改:
请记住, @first
, @second
和 @third
将随时被其他字符串替换。所以使用硬编码的NSRange值是行不通的。
Remember, @"first"
, @"second"
and @"third"
will be replaced by other strings at any time. So using hardcoded NSRange values won't work.
推荐答案
在构建属性字符串时,我更喜欢使用可变子类,只是为了保持清洁。
When building attributed strings, I prefer to use the mutable subclass, just to keep things cleaner.
话虽如此,这里是你如何创建一个三色属性字符串:
That being said, here's how you create a tri-color attributed string:
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"firstsecondthird"];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];
在浏览器中输入。 警告实现者
显然你不会在这样的范围内进行硬编码。也许你可以这样做:
Obviously you're not going to hard-code in the ranges like this. Perhaps instead you could do something like:
NSDictionary * wordToColorMapping = ....; //an NSDictionary of NSString => UIColor pairs
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@""];
for (NSString * word in wordToColorMapping) {
UIColor * color = [wordToColorMapping objectForKey:word];
NSDictionary * attributes = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
NSAttributedString * subString = [[NSAttributedString alloc] initWithString:word attributes:attributes];
[string appendAttributedString:subString];
[subString release];
}
//display string
这篇关于你如何使用NSAttributedString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!