How do I set the font size in a text cell so that the string fills the cell's rect?

后端 未结 6 1384
刺人心
刺人心 2020-12-30 15:13

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

6条回答
  •  别那么骄傲
    2020-12-30 15:55

    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.

提交回复
热议问题