多种颜色在一个NSString
or NSMutableStrings
是不可能的。所以我听说过一些关于NSAttributedString http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSAttributedString_Class/Reference/Reference.html这是与推出的iPad SDK 3.2(或 3.2 左右)并且可在 iPhone 上使用iPhone SDK 4.0 测试版.
我想要一根具有三种颜色的绳子。
我不使用 3 个单独的 NSString 的原因是因为这三个的长度NSAttributedString
子字符串经常变化,所以我宁愿不使用任何计算来重新定位 3 个单独的字符串NSString
对象。
如果可以的话使用NSAttributedString
我该如何进行以下操作 - (如果 NSAttributed 字符串不可能,你会怎么做):
Edit:记住,@"first"
, @"second"
and @"third"
随时会被其他字符串替换。因此使用硬编码的 NSRange 值是行不通的。
在构建属性字符串时,我更喜欢使用可变子类,只是为了让事情更干净。
话虽这么说,以下是创建三色属性字符串的方法:
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)];
typed in a browser. caveat implementor
显然,您不会在这样的范围内进行硬编码。也许你可以这样做:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)