tranvutuan
tranvutuan

Reputation: 6109

set colour for subscript, kCTForegroundColorAttributeName, ios

My target is to show cents as a superscript with small font in blue color. I am doing the following

        self.superScript      =   @"8899";
        NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:self.superScript];
        UIFont *font = [UIFont systemFontOfSize:18.0f];
        UIFont *smallFont = [UIFont systemFontOfSize:9.0f];

        [attString beginEditing];
        [attString addAttribute:NSFontAttributeName value:(font) range:NSMakeRange(0, self.superScript.length - 2)];
        [attString addAttribute:NSFontAttributeName value:(smallFont) range:NSMakeRange(self.superScript.length - 2, self.superScript.length - 2)];
        [attString addAttribute:(NSString*)kCTSuperscriptAttributeName value:@"2" range:NSMakeRange(self.superScript.length - 2, self.superScript.length - 2)];
        [attString addAttribute:(NSString*)kCTForegroundColorAttributeName value:(id)([[UIColor blueColor] CGColor]) range:NSMakeRange(self.superScript.length - 2, self.superScript.length - 2)];
        [attString endEditing];
        self.amount.attributedText = attString;

However what i am getting is enter image description here and the superscript is not in blue.

Any thoughts about this one.

Upvotes: 2

Views: 1945

Answers (2)

jnawaz
jnawaz

Reputation: 134

In iOS7

[attString addAttribute:(NSString*)kCTForegroundColorAttributeName value:(id)([[UIColor blueColor] CGColor]) range:NSMakeRange(self.superScript.length - 2, self.superScript.length - 2)];

does not work. Replace kCTForegroundColorAttributeName with

NSForegroundColorAttributeName

and pass in a regular UIColor object for value.

It will work in iOS 6 too if you need to support iOS 6 & 7.

Upvotes: 3

Michael Dautermann
Michael Dautermann

Reputation: 89509

This may just be a wrong attribute name issue, as I suspect you're not doing anything explicitly CoreText before or after this code.

For your attributed string, try using these attributes instead:

[attString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(self.superScript.length - 2, self.superScript.length - 2)];

Upvotes: 4

Related Questions