2010-07-24 10 views

Antwort

1

Ich verwendete Jerry Krinock ausgezeichnete NS (String) + Geometrics (located here) und eine kleine Methode wie folgt. Ich bin immer noch an einem einfacheren Weg interessiert.

- (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

Vergessen Sie nicht, in Superklassen zu suchen. Ein NSTextField ist eine Art NSControl, und jedes NSControl reagiert auf the sizeToFit message.

6

Ich habe es gelöst, indem Sie eine NSTextFieldCell-Unterklasse erstellen, die die Zeichenkette überschreibt. Es sieht aus, ob die Zeichenfolge passt und wenn nicht, wird die Schriftgröße verringert, bis sie passt. Dies könnte effizienter gemacht werden und ich habe keine Ahnung, wie es sich verhalten wird, wenn die cellFrame eine Breite von 0 hat. Trotzdem war es gut genug für meine Bedürfnisse.

- (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

Damit die Schrift korrekt vertikal zentriert wird, wird die folgende Zeile direkt vor dem 'while' benötigt:' [mutableAttributedString removeAttribute: @ "NSOriginalFont" -Bereich: NSMakeRange (0, [mutableAttributedString length])]; ' – DarkDust

Verwandte Themen