如何让NSTextField自动调整字体大小以适应文本?
答
我用Jerry Krinock的优秀NS(Attributed)String + Geometrics (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];
}
答
我已经通过创建覆盖字符串绘图的NSTextFieldCell子类来解决它。它看起来该字符串是否合适,如果不合适,它会减小字体大小直到它合适。这可能会变得更加高效,我不知道cellFrame
的宽度为0时它的表现如何。尽管如此,它还是符合我的需求的Good Enough™。
- (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
为了正确地使字体垂直居中,紧接在'while'之前需要以下行:[mutableAttributedString removeAttribute:@“NSOriginalFont”range:NSMakeRange(0,[mutableAttributedString length])];' – DarkDust 2014-03-04 10:11:33
我为别人回答了这个问题。你可以看到我的答案[这里](http://stackoverflow.com/questions/2908704/get-nstextfield-contents-to-scale/2911982#2911982)。 – regulus6633 2010-07-24 20:06:20