-2

我正在尝试为标签设置文本。我想为不同的句子设置不同的字体大小和颜色。说

#define Label @"This is a label Title. This is label subscript"

在这里,我需要一种字体的“这是一个标签标题”。以及其他字体的“这是标签下标”。可能吗。我试着做

#define Label @"This is a label Title. <b>This is label subscript <b>"和其他几件事。但没有变化。

谢谢吉腾

4

2 回答 2

1

字符串没有字体。您需要设置标签本身的字体,或使用属性字符串

下面是一个简单示例,说明如何在属性字符串中使用多个属性:

NSString *s1 = @"Hello ";
NSString *s2 = @"World";

NSDictionary *attr1 = [NSDictionary dictionaryWithObjectsAndKeys:
    [UIFont fontWithName:@"Arial" size:20] , NSFontAttributeName, nil];

NSDictionary *attr2 = [NSDictionary dictionaryWithObjectsAndKeys:
    [UIFont fontWithName:@"Georgia" size:40] , NSFontAttributeName, nil];

NSMutableAttributedString *as = [[NSMutableAttributedString alloc] 
    initWithString:[s1 stringByAppendingString:s2] attributes:attr1];

[as setAttributes:attr2 range:NSMakeRange(s1.length, s2.length)];

要将文本放入标签中,您可以使用:

myLabel.attributedText = as;

我建议不要将这种格式放在宏中,因为代码变得混乱且难以维护。

于 2013-04-12T11:26:06.450 回答
0

您可以使用此方法。

+ (void)setMultiColorAndFontText:(NSString *)text rangeString:(NSArray *)rangeString label:(UILabel*) label font:(NSArray*) fontName color:(NSArray*) colorName{
label.layer.sublayers = nil;

NSMutableAttributedString *mutableAttributedString = [[ NSMutableAttributedString alloc]initWithString:text];

for (int i =0 ; i<[rangeString count]; i++)
{
    CTFontRef  ctFont = CTFontCreateWithName((__bridge CFStringRef) [UIFont fontWithName:[fontName objectAtIndex:i] size:10.0].fontName, [UIFont fontWithName:[fontName objectAtIndex:i] size:10.0].pointSize, NULL);

    NSRange whiteRange = [text rangeOfString:[rangeString objectAtIndex:i]];

    if (whiteRange.location != NSNotFound)
    {
        [mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)[colorName objectAtIndex:i] range:whiteRange];
        [mutableAttributedString addAttribute:(NSString*)kCTFontAttributeName
                                        value:( __bridge id)ctFont
                                        range:whiteRange];
    }
}

CGSize expectedLabelSize = [text sizeWithFont:[UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:10.0f] constrainedToSize:CGSizeMake(186,100) lineBreakMode:UILineBreakModeWordWrap];

CATextLayer   *textLayer = [[CATextLayer alloc]init];
textLayer.frame =CGRectMake(0,0, label.frame.size.width,expectedLabelSize.height+4);
textLayer.contentsScale = [[UIScreen mainScreen] scale];
textLayer.string=mutableAttributedString;
textLayer.opacity = 1.0;
textLayer.alignmentMode = kCAAlignmentLeft;
[label.layer addSublayer:textLayer];
[textLayer setWrapped:TRUE];

label.lineBreakMode = UILineBreakModeWordWrap;

[label setText:@""];

}

使用此方法,您可以在同一标签中显示不同大小和不同颜色的文本。

于 2013-04-12T11:35:42.360 回答