2012-02-23 7 views
6

enter image description herekCTSuperscriptAttributeName no está funcionando para el uso de subíndices y superíndices

estoy usando el código para la visualización de subíndices y superíndices en la etiqueta, pero no de trabajo.

Creo una categoría para 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]; 
} 
+0

¿Puedes mostrar cómo lo llamas? – NSCry

+0

http://stackoverflow.com/questions/9284077/how-do-i-include-superscripts-in-nsstring cheque esta – NSCry

+0

Estoy llamando de la siguiente manera: * NSMutableAttributedString attrStr = [NSMutableAttributedString attributedStringWithString: @ "H2O" ]; [attrStr setSubscript: YES range: [txt rangeOfString: @ "2"]]; \t \t label1.attributedText = attrStr; –

Respuesta

3

El problema es que muchas fuentes bien no definen variantes super- y subíndice, o tienen algunas bastante moderno (hablar mal) métricas para ello.

Una posible solución es falsificarla, como con el método siguiente (en una categoría en NSMutableAttributedString). Tiene algunos defectos sin embargo:

  • La anchura del trazo no es perfecto, especialmente para los tamaños de letra más grande
  • Es algo más difícil de deshacer
  • El tamaño calculado y compensado no puede ser perfecto para algunas fuentes

En el lado positivo, esto debería funcionar para todas las fuentes, y si es necesario puede modificarse para fines específicos.

- (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 *[email protected]{ 
     NSFontAttributeName:   siFont, 
     NSBaselineOffsetAttributeName: @(blOffset), 
    }; 

    [self addAttributes:attrs range:range]; 
} 
Cuestiones relacionadas