你如何使用 NSAttributedString? [英] How do you use NSAttributedString?

查看:25
本文介绍了你如何使用 NSAttributedString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NSStringNSMutableStrings 中的多种颜色是不可能的.所以我听说过一些关于 NSAttributedStringiPad SDK 3.2(或大约 3.2)一起引入,从 iPad SDK 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屋!

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