仅供参考,上面建议使用 DAAttributedStringUtils 和 DAAttributedLabel 的答案没有提到这些是使用 NSAttributedString 的便利类。它们使格式化 NSAttributedString 实例更容易一些。例如,下面是如何使用 DAAttributedStringUtils 执行 HAS 所描述的相同格式:
float finalPrice = 34.99, shipping = 4.99;
// Setup the formatter
DAAttributedStringFormatter* formatter = [[DAAttributedStringFormatter alloc] init];
formatter.defaultFontFamily = @"Georgia";
formatter.defaultFontSize = 12.0f;
formatter.colors = @[ [UIColor blackColor], [UIColor redColor] ];
NSAttributedString* attrStr = [formatter formatString:@"%0C%0FRed Courier Text %1C%1FBlue Arial Text %0CRed Arial Text"];
// setup base strings
NSString *finalStr = @"Some Text. ";
NSString *shippingAttributed = [NSString stringWithFormat:@"%%B%%1C$%.2f%%b%%c", shipping];
NSString *middleText0 = @"Final price including ";
NSString *middleText1 = @" Shipping and all discount: ";
NSString *finalPriceAttributed = [NSString stringWithFormat:@"%%B%%1C$%.2f%%b%%c", finalPrice];
// Format the strings
self.label.attributedText = [formatter formatString:[NSString stringWithFormat:@"%@%@%%B%%1C%@%%b%%c%@%%B%%1C%@", finalStr, shippingAttributed, middleText0, middleText1, finalPriceAttributed];
代码少了一些,我觉得更容易理解。仅供参考,最后一行中的格式化程序字符串包含用于修改字符串部分格式的代码。这些代码使用双百分比(