Search code examples
iosuilabelnsdictionarynsmutableattributedstring

How to set NSMutableAttributedString into two lines


I want to create a single UILablel like this. enter image description here

I want to set year font to HElvaticaNeu-medium and the 2015 into HelvaticaNeu. And I need these two strings to appear in 2 lines just like in this image.

How I can do this. I set two seperate NSMutableAttributedString in this way.

UIFont *helMedium = [UIFont fontWithName:@"HelveticaNeue-Medium" size:12.0];
NSDictionary *mediumDict = [NSDictionary dictionaryWithObject: helMedium forKey:NSFontAttributeName];
NSMutableAttributedString *mAttrString = [[NSMutableAttributedString alloc] initWithString:@"Year :" attributes: mediumDict];

UIFont *helNormal = [UIFont fontWithName:@"HelveticaNeue" size:12.0];
NSDictionary *normalDict = [NSDictionary dictionaryWithObject: helNormal forKey:NSFontAttributeName];
NSMutableAttributedString *nAttrString = [[NSMutableAttributedString alloc] initWithString:@"2016" attributes: normalDict];

Now how should I set this 2 strings in two lines? Does anyone have an idea?


Solution

  • you need to append the second string to first string

    Use this code.

    UIFont *helMedium = [UIFont fontWithName:@"HelveticaNeue-Medium" size:12.0];
    NSDictionary *mediumDict = [NSDictionary dictionaryWithObject: helMedium forKey:NSFontAttributeName];
    NSMutableAttributedString *mAttrString = [[NSMutableAttributedString alloc] initWithString:@"Year :" attributes: mediumDict];
    
    UIFont *helNormal = [UIFont fontWithName:@"HelveticaNeue" size:12.0];
    NSDictionary *normalDict = [NSDictionary dictionaryWithObject: helNormal forKey:NSFontAttributeName];
    NSMutableAttributedString *nAttrString = [[NSMutableAttributedString alloc] initWithString:@"\n2016" attributes: normalDict];
    
    [mAttrString appendAttributedString:nAttrString];
    
    label.attributedText = mAttrString;