How to get height for NSAttributedString at a fixed width

后端 未结 12 1077
萌比男神i
萌比男神i 2020-12-12 18:53

I want to do some drawing of NSAttributedStrings in fixed-width boxes, but am having trouble calculating the right height they\'ll take up when drawn. So far, I\'ve tried:

12条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 19:46

    On OS X 10.11+, the following method works for me (from Apple's Calculating Text Height document)

    - (CGFloat)heightForString:(NSAttributedString *)myString atWidth:(float)myWidth
    {
        NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:myString];
        NSTextContainer *textContainer = [[NSTextContainer alloc] initWithContainerSize:
            NSMakeSize(myWidth, FLT_MAX)];
        NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
        [layoutManager addTextContainer:textContainer];
        [textStorage addLayoutManager:layoutManager];
        [layoutManager glyphRangeForTextContainer:textContainer];
        return [layoutManager
            usedRectForTextContainer:textContainer].size.height;
    }
    

提交回复
热议问题