2010-07-24 17 views

Respuesta

1

Utilicé la excelente cadena NS (atribuida) de Jerry Krinock + Geometrics (located here) y un pequeño método como el siguiente. Todavía estoy interesado en una forma más simple.

- (void) prepTextField:(NSTextField *)field withString:(NSString *)string 
{ 
    #define kMaxFontSize 32.0f 
    #define kMinFontSize 6.0f 
    float fontSize = kMaxFontSize; 
    while (([string widthForHeight:[field frame].size.height font:[NSFont systemFontOfSize:fontSize]] > [field frame].size.width) && (fontSize > kMinFontSize)) 
    { 
      fontSize--; 
    } 
    [field setFont:[NSFont systemFontOfSize:fontSize]]; 

    [field setStringValue:string]; 

    [self addSubview:field]; 
} 
2

No olvides buscar en superclases. Un NSTextField es una especie de NSControl, y cada NSControl responde al the sizeToFit message.

6

Lo he resuelto creando una subclase NSTextFieldCell que anula el dibujo de la cadena. Se ve si la cadena se ajusta y si no disminuye el tamaño de la fuente hasta que encaje. Esto podría hacerse más eficiente y no tengo idea de cómo se comportará cuando el cellFrame tenga un ancho de 0. Sin embargo, fue Good Enough ™ para mis necesidades.

- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView 
{ 
    NSAttributedString *attributedString; 
    NSMutableAttributedString *mutableAttributedString; 
    NSSize stringSize; 
    NSRect drawRect; 

    attributedString = [self attributedStringValue]; 

    stringSize = [attributedString size]; 
    if (stringSize.width <= cellFrame.size.width) { 
     // String is already small enough. Skip sizing. 
     goto drawString; 
    } 

    mutableAttributedString = [attributedString mutableCopy]; 

    while (stringSize.width > cellFrame.size.width) { 
     NSFont *font; 

     font = [mutableAttributedString 
      attribute:NSFontAttributeName 
      atIndex:0 
      effectiveRange:NULL 
     ]; 
     font = [NSFont 
      fontWithName:[font fontName] 
      size:[[[font fontDescriptor] objectForKey:NSFontSizeAttribute] floatValue] - 0.5 
     ]; 

     [mutableAttributedString 
      addAttribute:NSFontAttributeName 
      value:font 
      range:NSMakeRange(0, [mutableAttributedString length]) 
     ]; 

     stringSize = [mutableAttributedString size]; 
    } 

    attributedString = [mutableAttributedString autorelease]; 

drawString: 
    drawRect = cellFrame; 
    drawRect.size.height = stringSize.height; 
    drawRect.origin.y += (cellFrame.size.height - stringSize.height)/2; 
    [attributedString drawInRect:drawRect]; 
} 
+0

Para hacer que la fuente se centre verticalmente correctamente, se necesita la siguiente línea justo antes del rango 'while':' [mutableAttributedString removeAttribute: @ "NSOriginalFont": NSMakeRange (0, [mutableAttributedString length])]; ' – DarkDust

Cuestiones relacionadas