简体   繁体   English

如何垂直对齐状态栏项目文本?

[英]How can I vertically align my status bar item text?

在此输入图像描述

Left one on the picture is the date and time from Apple and one is my application one. 图中左边的一个是来自Apple的日期和时间,一个是我的应用程序之一。 As you may see the text of my application appears lower than the Apple one. 您可能会看到我的应用程序文本显示低于Apple的文本。 Which doesn't look pretty. 哪个看起来不漂亮。 How can this be resolved? 怎么解决这个问题?

self.statusBarItem.image                    = nil
self.statusBarItem.button?.imagePosition    = .NoImage
self.statusBarItem.button?.title            = "Sun 5 Jun  13:35"

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 在这种情况下您实际想要做的是设置NSAttributedString.Key.baselineOffset ,您可以在其中导出基线值,如下所示

    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. 这里的免责声明是我不完全确定displayScale部分。 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 基于此,我得到了灵感: 在NSAttributedString中垂直居中两种不同大小的字体

If this technique is wrong, I'd be interested to know so I can fix it. 如果这种技术错了,我有兴趣知道,所以我可以解决它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM