ios - 你如何使用 NSAttributedString?

标签 ios ios4 nsattributedstring textcolor

NSStringNSMutableStrings 中的多种颜色是不可能的。所以我听说过一些关于 NSAttributedString 的事它与 iPad SDK 3.2(或大约 3.2)一起引入,并在 iPhone SDK 4.0 beta 的 iPhone 上可用。

我想要一个具有三种颜色的字符串。

我不使用 3 个单独的 NSString 的原因是因为三个 NSAttributedString 子字符串的长度经常变化,所以我宁愿不使用任何计算来重新定位 3单独的 NSString 对象。

如果可以使用 NSAttributedString,我应该如何进行以下操作(如果不能使用 NSAttributed 字符串,您会怎么做):

alt text

编辑: 请记住,@"first"@"second"@"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)];

在浏览器中输入。 警告实现者

显然,您不会在这样的范围内进行硬编码。也许你可以做类似的事情:

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

关于ios - 你如何使用 NSAttributedString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3482346/

相关文章:

ios - 显示 : flex; doesn't work on iPad (both Chrome and Safari)

iphone - iOS - 恢复自动续订订阅

ios - NSForegroundColorAttributeName 不适用于 UILabel

cocoa - 设置 NSTextView

ios - 是否可以获得 NSMutableAttributedString 的属性和范围列表?

ios - Xcode 6 创建 Storyboard警告

ios - 应用内购买产品价格

ios - UITableViewCell 选择挑战

objective-c - MFMessageComposeViewController 中的界面语言

iphone - 当我将它们翻译成另一种语言时,正则表达式是否有效?