How can I vertically align my status bar item text? How can I vertically align my status bar item text? swift swift

How can I vertically align my status bar item text?


You could do it in offset. You cannot do it like this since it needs to be done on the status item button bar.

button.frame = CGRectMake(0.0, 0.5, button.frame.width, button.frame.height)


I wanted to make a quick addition to this. While the accepted answer does indeed work based on the context of the question. It will not work if you have an image, as this moves everything (image and text). I have found for some reason, the image is vertically centered, but the text is not.

What you actually want to do in that case is set NSAttributedString.Key.baselineOffset, where you derive the baseline value as follows

    var displayScale: CGFloat = 1.0    let pstyle = NSMutableParagraphStyle()    pstyle.alignment = .center;    let aStr = NSAttributedString(string: str, attributes: [NSAttributedString.Key.paragraphStyle: pstyle, NSAttributedString.Key.font: font])    if let main = NSScreen.main {        displayScale = main.backingScaleFactor        if displayScale <= 0.0 {            displayScale = 1.0        }    }    let textHeight = aStr.size().height    baselineOffset = ((font.ascender - font.descender) - textHeight) / displayScale    button.attributedTitle =  = NSAttributedString(string: str, attributes: [NSAttributedString.Key.paragraphStyle: pstyle, NSAttributedString.Key.baselineOffset: baselineOffset, NSAttributedString.Key.font: font])

Disclaimers here are that I'm not completely sure about the displayScale part. I theorize this is needed to correct for pixels/points.

I've only added this answer because I was struggling to find a good answer for this. I got my inspiration to do this based on this: Center two fonts with different different sizes vertically in an NSAttributedString

If this technique is wrong, I'd be interested to know so I can fix it.