NSAttributedString是否有任何类似的?

通常我在界面生成器中构build应用程序界面。 有时候devise需要使用属性string(字体,颜色等)。 如果string是静态的,configuration很容易。
但是,如果string是dynamic的(带参数的格式),那么在接口生成器中没有办法configuration属性。 它需要写很多代码。
我正在寻找[NSString stringWithFormat:][NSString stringWithFormat:]一些类似物。 所以我可以在接口生成器中设置string格式和必要的属性,然后在代码中提供必要的参数。

例如:
让我们考虑一下,我需要使用如下格式的显示string:“ %d + %d = %d ”(所有数字都是粗体)。
我想在界面生成器中configuration这种格式。 在代码中,我想提供参数:1,1,2。应用程序应显示“ 1 + 1 = 2 ”。

这里是我写的一个类添加到NSAttributedString的方法。 但是,您必须将NULL作为函数的最后一个parameter passing,否则将会崩溃到检测大小的va_list限制。 [归档stringstringWithFormat:attrFormat,attrArg1,attrArg2,NULL];

 @implementation NSAttributedString(stringWithFormat) +(NSAttributedString*)stringWithFormat:(NSAttributedString*)format, ...{ va_list args; va_start(args, format); NSMutableAttributedString *mutableAttributedString = (NSMutableAttributedString*)[format mutableCopy]; NSString *mutableString = [mutableAttributedString string]; while (true) { NSAttributedString *arg = va_arg(args, NSAttributedString*); if (!arg) { break; } NSRange rangeOfStringToBeReplaced = [mutableString rangeOfString:@"%@"]; [mutableAttributedString replaceCharactersInRange:rangeOfStringToBeReplaced withAttributedString:arg]; } va_end(args); return mutableAttributedString; } @end 

我正在寻找这个问题的现有解决scheme,但没有成功。
所以我能够自己实现它。
这就是为什么我自我回答这个问题,与社区分享知识。

NSAttributedString + VPAttributedFormat类别提供了基于属性格式和参数来构build属性string的方法,这些格式和参数应该满足这种格式。
使用此类别的最适合的情况是在界面构build器中configuration了可变属性文本的文本控件。
您需要将正确的string格式设置为归因文本并configuration必要的属性。
然后你需要通过使用这个类别的方法在代码中传递必要的参数。

  • 格式语法与[NSString stringWithFormat:]方法相同;
  • 可以用在Objective C和Swift代码中;
  • 需要iOS 6.0及更高版本;
  • 与CocoaPods整合;
  • 覆盖unit testing。

用法

1.导入框架头或模块

 // Objective C // By header #import <VPAttributedFormat/VPAttributedFormat.h> // By module @import VPAttributedFormat; 

 // Swift import VPAttributedFormat 

2.在界面构build器中为文本控件设置正确的格式和属性
用法

3.创buildIBOutlet并将其与文本控件链接

 // Objective C @property (nonatomic, weak) IBOutlet UILabel *textLabel; 

 // Swift @IBOutlet weak var textLabel: UILabel! 

4.用必要的参数填充格式

 // Objective C NSString *hot = @"Hot"; NSString *cold = @"Cold"; self.textLabel.attributedText = [NSAttributedString vp_attributedStringWithAttributedFormat:self.textLabel.attributedText, hot, cold]; 

 // Swift let hot = "Hot" let cold = "Cold" var arguments: [CVarArgType] = [hot, cold] textLabel.attributedText = withVaList(arguments) { pointer in NSAttributedString.vp_attributedStringWithAttributedFormat(textLabel.attributedText, arguments: pointer) } 

5.查看结果
结果

例子

VPAttributedFormatExample是一个示例项目。 它提供了Basic和Pro格式的例子。
例