KCTSuperscriptAttributeName does not work for using index and superstructure

enter image description here

I use this code to display an index and a superscript in a label, but it does not work.

I am creating a category for NSAttributedString .

 -(void)setSuperscript:(BOOL)isSuperscript range:(NSRange)range { [self removeAttribute:(NSString * )kCTSuperscriptAttributeName range:range]; // Work around for Apple leak [self addAttribute:(NSString*)kCTSuperscriptAttributeName value:[NSNumber numberWithInt:(isSuperscript?1:0)] range:range]; } -(void)setSubscript:(BOOL)isSubscript range:(NSRange)range { [self removeAttribute:(NSString * )kCTSuperscriptAttributeName range:range]; // Work around for Apple leak [self addAttribute:(NSString*)kCTSuperscriptAttributeName value:[NSNumber numberWithInt:(isSubscript?-1:0)] range:range]; } 
+6
source share
1 answer

The problem is that many fonts do not define super- and indexes or have some pretty funky (speaking incorrect) metrics for it.

A possible workaround is fake, as using the method below (in the category in NSMutableAttributedString). It has some disadvantages:

  • The stroke width is not perfect, especially for large font sizes
  • Harder to undo
  • The calculated size and offset may not be ideal for some fonts.

On the positive side, this should work for all fonts, and if necessary, can be changed for certain purposes.

 - (void)fakeSuperOrSubScript:(BOOL)superscript range:(NSRange)range defaultFont:(NSFont *)defaultFont { NSFontManager *fm=[NSFontManager sharedFontManager]; NSFont *font=[self attribute:NSFontAttributeName atIndex:range.location effectiveRange:NULL ]; if(!font) font=defaultFont; if(!font) { NSLog(@"ERROR: fakeSuperOrSubScript has no font to use!"); return; } // Bolden font to adjust stroke width NSFont *siFont=[fm convertWeight:YES ofFont:font]; float originalSize=[siFont pointSize]; float newSize=originalSize*3.0/4.0; float blOffset=(superscript)?originalSize/2.0:-originalSize/4.0; siFont=[fm convertFont:siFont toSize:newSize]; NSDictionary * attrs=@ { NSFontAttributeName: siFont, NSBaselineOffsetAttributeName: @(blOffset), }; [self addAttributes:attrs range:range]; } 
+3
source

Source: https://habr.com/ru/post/909172/


All Articles