将NSString转换为HTML并将HTML文本设置为UILabel

时间:2013-04-29 06:45:33

标签: objective-c nsstring uilabel

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

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

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

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

3 个答案:

答案 0 :(得分:2)

使用以下标签表示粗体效果。或者你可以从那个类中获取代码。

DAAttributedStringUtils

也看到了这个

Different Label

修改

    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];

答案 1 :(得分:0)

尝试使用NSAttributedString

这里有几个问题就像这样 How do you use 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 +

答案 2 :(得分: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];

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