I have a view that contains two NSTextFieldCells. The size at which these cells are drawn is derived from the size of the view, and I want the text in each cell
It was recommended out of band that I try a binary search for an appropriate size. This is a very limited example of that:
- (NSFont *)labelFontForText: (NSString *)text inRect: (NSRect)rect {
CGFloat prevSize = 0.0, guessSize = 16.0, tempSize;
NSFont *guessFont = nil;
while (fabs(guessSize - prevSize) > 0.125) {
guessFont = [NSFont labelFontOfSize: guessSize];
NSSize textSize = [text sizeWithAttributes:
[NSDictionary dictionaryWithObject: guessFont
forKey: NSFontAttributeName]];
if (textSize.width > rect.size.width ||
textSize.height > rect.size.height) {
tempSize = guessSize - (guessSize - prevSize) / 2.0;
}
else {
tempSize = guessSize + (guessSize - prevSize) / 2.0;
}
prevSize = guessSize;
guessSize = tempSize;
}
return [[guessFont retain] autorelease];
}
The limitations (you'd better not need a 32pt or larger font, or anything that ain't Lucida Grande) are not important for my need, but certainly would put some people off using this method. I'll leave the question open, and accept a more robust approach.