Search code examples
iosobjective-cnsmutableattributedstring

Apply text colour and subscript to NSMutableString in objective-c


I am unable to apply both the attributes at the same. Either only color or subscript am able to apply. Here is my code

NSMutableAttributedString * attributedText = [[NSMutableAttributedString alloc]initWithString:@"some text"];

[attributedText addAttribute:NSFontAttributeName
                            value:[UIFont fontWithName:@"Lato-Bold" size:16]
                            range:NSMakeRange(14,1)];
[attributedText addAttribute:(NSString *)kCTSuperscriptAttributeName value:@-1 range:NSMakeRange(14,1)];

[attributedText addAttribute:(NSString *)kCTForegroundColorAttributeName value:@{ NSForegroundColorAttributeName : [UIColor colorWithRed:85.0/255.0 green:38.0/255.0 blue:152.0/255.0 alpha:1.0] } range:(NSRange){0,6}];

Solution

  • You can try with this code

    [str addAttribute:(NSString *)kCTSuperscriptAttributeName value:@-1 range:NSMakeRange(14,1)];
    
    [str setAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor]}
                  range:(NSRange){0,7}];