如何在标签内的单个字符串上使用多种字体样式?

时间:2012-12-28 11:41:04

标签: iphone objective-c uilabel

我有一个由 -

组成的字符串
lblWithText.backgroundColor = [UIColor clearColor];
    lblWithText.textColor = [UIColor blackColor];
    lblWithText.font = [UIFont fontWithName:@"Helvetica" size:12.0];
    lblWithText.text = [NSString stringWithFormat:@"Blah1:blah-blah%d. Blah2:-%d%%", [currentCoupon.couponPrice intValue],[currentCoupon.couponDiscountPercent intValue]];

请告诉我怎么做“Blah2: - %d %%”“是博尔登? 提前谢谢

4 个答案:

答案 0 :(得分:6)

可能这可以帮到你

Bold & Non-Bold Text In A Single UILabel?

它有适用于iOS 6和iOS5的解决方案,你必须使用带有NSAttributedString的CATextLayer

或者您可以参考http://www.cocoacontrols.com/platforms/ios/controls/ohattributedlabel

https://github.com/AliSoftware/OHAttributedLabel/

https://github.com/mattt/TTTAttributedLabel/

答案 1 :(得分:4)

只需要{BOLD的Helvetica字体名称

lblWithText.font = [UIFont fontWithName:@"Helvetica-Bold" size:12.0];

只是一个例子..

UILable *lbl1 = [[UILable alloc]init];
lbl1.frame = CGRectMake(10,10,100,40);
lbl1.backgroundColor = [UIColor clearColor];
lbl1.textColor = [UIColor blackColor];
lbl1.font = [UIFont fontWithName:@"Helvetica" size:12.0];
lbl1.text = @"Stack";

UILable *lbl2 = [[UILable alloc]init];
lbl2.frame = CGRectMake(110,10,150,40);
lbl2.backgroundColor = [UIColor clearColor];
lbl2.textColor = [UIColor blackColor];
lbl2.font = [UIFont fontWithName:@"Helvetica-Bold" size:12.0];
lbl2.text = @"OverFlow";

[self.view addSubview:lbl1];
[self.view addSubview:lbl2];

这是一个通过你了解的例子..

<强>更新

另请参阅此示例,其中包含NSMutableAttributedString:

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"Blah1:blah-blah%d. Blah2:-%d%%", [currentCoupon.couponPrice intValue],[currentCoupon.couponDiscountPercent intValue]];
[str addAttribute:NSBackgroundColorAttributeName value:[UIColor clearColor] range:NSMakeRange(0,30)];/// Define Range here and also BackGround color which you want
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,30)];/// Define Range here and also TextColor color which you want
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:20.0] range:NSMakeRange(20, 10)];
lblWithText.attributedText = str;

答案 2 :(得分:1)

对于完整的粗体,您可以尝试使用此

[lblWithText setFont:[UIFont fontWithName:@"Helvetica-Bold" size:12.f]]

还可以转到此链接查看各种fonts

正如你所说,你想要一些正常的粗体部分,那么你可以尝试使用attributionString,但不确定。

或转到此linkthis

答案 3 :(得分:1)

为此使用NSMutableAttributedString请按照本教程获取NSMutableAttributedString

http://soulwithmobiletechnology.blogspot.in/2012/07/how-to-use-nsattributedstring-in-ios-6.html