代码之家  ›  专栏  ›  技术社区  ›  refulgentis

如何告诉nstextfield自动调整字体大小以适应文本?[副本]

  •  11
  • refulgentis  · 技术社区  · 14 年前

    这个问题已经有了答案:

    从本质上寻找可可 [UILabel adjustsFontSizeToFitWidth] 是。

    3 回复  |  直到 11 年前
        1
  •  6
  •   DarkDust    11 年前

    我通过创建一个nstextfieldsell子类来解决这个问题,它覆盖了字符串绘制。它检查字符串是否合适,如果不合适,它会减小字体大小,直到合适为止。这可以提高效率,我不知道当 cellFrame 宽度为0。不过,这足以满足我的需要。

    - (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];
    }
    
        2
  •  2
  •   Peter Hosey    14 年前

    别忘了看超类。nstextfield是一种nscontrol,每个nscontrol都响应 the sizeToFit message .

        3
  •  1
  •   refulgentis    14 年前

    我用了杰里·克里诺克的优秀的ns(归因)弦+几何。 (located here) 一个像下面这样的小方法。我仍然对更简单的方法感兴趣。

    - (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];
    }