2

是否可以将 NSString 转换为 html 并设置为标签?

下面的代码显示了我想将 finalPrice 设置为粗体文本并将 finalStr&shipping 字符串设置为普通文本的 NSString

NSString *myText = [NSString 
     stringWithFormat:
       @"%@\nFinal price including $%.2f Shipping and all discount: <b>$%.2f</b>",
      finalStr,shipping,finalPrice];
lbl.text = myText;

我想将多种颜色和多种文本类型设置为同一个动态标签。

4

3 回答 3

2

使用以下标签以获得粗体效果。或者您可以从该类中获取代码。

DAAttributedStringUtils

也看到这个

不同的标签

编辑

    NSString *myText = [NSString stringWithFormat:@"%@\nFinal price including $%.2f Shipping and all discount: %%B$%.2f%%b",finalStr,shipping,finalPrice];


     DAAttributedLabel* lbl = [[DAAttributedLabel alloc] initWithFrame:CGRectMake(30.0f, 30.0f, 260.0f, 24.0f)];
     lbl.backgroundColor = [UIColor colorWithRed:0.9f green:0.9f blue:1.0f alpha:1.0f]; 
     lbl.text = (id)[formatter formatString:myText];
     [self.view addSubview:lbl];
于 2013-04-29T06:53:23.350 回答
0

尝试使用NSAttributedString

这里已经有几个问题,比如 你如何使用 NSAttributedString?

NSString * textString = @"Hello Bold";
NSInteger _stringLength = [textString length];
NSMutableAttributedString * attString = [[NSMutableAttributedString alloc] initWithString:textString];

[attString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica" size:14.0f]; range:NSMakeRange(0, _stringLength)];

[attString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-Bold" size:14.0f]; range:NSMakeRange(6, 4)];

myLabel.attributedText = attString; 

(代码未测试)

编辑:label.attributedText 仅适用于 iOS 6.0+

于 2013-04-29T07:06:54.247 回答
0

仅供参考,上面建议使用 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];

代码少了一些,我觉得更容易理解。仅供参考,最后一行中的格式化程序字符串包含用于修改字符串部分格式的代码。这些代码使用双百分比(

于 2013-04-29T22:26:46.473 回答