How can I vertically align my status bar item text?

落花浮王杯 提交于 2019-12-05 02:34:13
Tarvo Mäesepp

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!