#define值中的不同文本字体 - iOS

时间:2013-04-12 11:20:11

标签: iphone ios fonts colors uialertview

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

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

这里我需要一种字体“这是一个标签标题”。并且“这是标签下标”的其他字体。可能吗。我尝试过做

#define Label @"This is a label Title. <b>This is label subscript <b>"以及其他一些事情。但没有变化。

由于 Jithen

2 个答案:

答案 0 :(得分:1)

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

以下是如何在属性字符串中使用多个属性的简单示例:

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;

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

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

}

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