ref*_*tis 11 cocoa objective-c
寻找基本上与Cocoa相当的东西[UILabel adjustsFontSizeToFitWidth].
我通过创建一个覆盖字符串绘图的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];
}
Run Code Online (Sandbox Code Playgroud)
我使用了 Jerry Krinock 优秀的 NS(Attributed)String+Geometrics (位于此处)和如下所示的小方法。我仍然对更简单的方法感兴趣。
- (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];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8198 次 |
| 最近记录: |