Misaligned NSAttributedString in macOS NSStatusItem's button

79 views Asked by At

I would like to display a two-line NSAttributedString as the button title of the NSStatusItem of my macOS app.
However, it seems to move the text up a few pixels and, thus, cut it off. This problem did not occur before macOS Big Sur.

actual

Workaround

With some effort I managed to generate an NSImage of the text and use it as the button's image.

expected

Question

Is there any way to position the NSAttributedString correctly without using an image?

1

There are 1 answers

0
lucas lu On

I found a way to workaround this problem, but I don’t know if this way is correct, the code with Objetive-C is as follows

NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
CGFloat minMaxLineHeight = (font.pointSize - font.ascender + font.capHeight);
[style setMinimumLineHeight:minMaxLineHeight];
[style setMaximumLineHeight:minMaxLineHeight];
NSRange range = NSMakeRange(0, text.length);
[attriString addAttribute:NSParagraphStyleAttributeName
                       value:style
                       range:range];
[attriString addAttribute:NSBaselineOffsetAttributeName
                       value:@(-3.5)
                       range:range];