2010-07-24 12 views

Odpowiedz

1

Użyłem doskonałego NS (przypisanego) ciągu Jerry'ego Krinocka + Geometrics (located here) i małej metody podobnej do poniższej. Nadal jestem zainteresowany prostszym sposobem.

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

Nie zapomnij zajrzeć do superklatek. NSTextField jest rodzajem NSControl, a każdy NSControl odpowiada na the sizeToFit message.

6

Rozwiązałem go, tworząc podklasę NSTextFieldCell, która przesłania rysunek ciągu. Wygląda na to, czy łańcuch pasuje, a jeśli nie, zmniejsza rozmiar czcionki, aż do jej dopasowania. To może być bardziej efektywne i nie mam pojęcia, jak to będzie zachowywać się, gdy cellFrame ma szerokość 0. Niemniej jednak było Good Enough ™ dla moich potrzeb.

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

Aby czcionka była prawidłowo wycentrowana pionowo, potrzebny jest następujący wiersz tuż przed 'while':' [mutableAttributedString removeAttribute: @ "NSOriginalFont" zakres: NSMakeRange (0, [mutableAttributedString length])]; ' – DarkDust

Powiązane problemy