答案 0 :(得分:6)
我通过创建一个覆盖字符串绘图的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];
}
答案 1 :(得分:2)
答案 2 :(得分:1)