简体   繁体   English

如何水平对齐状态栏项目文本?

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

I'm learning swift so I'm starting off with a clock app.我正在快速学习,所以我开始使用时钟应用程序。 I'm able to get it working but the styling is not what I expected.我能够让它工作,但样式不是我所期望的。 When the time changes the whole title shifts.当时间改变时,整个标题就会改变。 Is it possible to keep text from shifting around?是否可以防止文本移动?

Here's what's happening: https://imgur.com/A5yj6CI.gif这是正在发生的事情: https : //imgur.com/A5yj6CI.gif

guard let statusButton = statusBarItem.button else { return }
let formatter = DateFormatter()

let timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in
  formatter.dateFormat = "hh:mm:ss.S"
  let dateTimeString = formatter.string(from: Date())
  statusButton.title = dateTimeString
}

Is align left the solution?左对齐是解决方案吗? If not, what are some options?如果没有,有哪些选择?

Left aligned the label will not help to solve your problem if your label doesn't have enough space to accommodate the shifting (due to the label value that's constantly changing) thus I believe you can solve it by setting up a fixed width constraint for your label.如果您的标签没有足够的空间来容纳移位(由于标签值不断变化),则左对齐标签将无助于解决您的问题,因此我相信您可以通过为您的标签设置固定宽度约束来解决它标签。

First of all you need to set your label with the most maximum possible label value, ie 99:99:99.9 in your case, the see how much the value of the label width.首先,您需要将标签设置为最大可能的标签值,即在您的情况下为 99:99:99.9,看看标签宽度的值是多少。

在此处输入图片说明

Then set the width constraint for your label.然后为您的标签设置宽度约束。

在此处输入图片说明

And finally set constraint value need to be slightly larger than the widest possible width that you have seen at the first step.最后设置的约束值需要比你在第一步看到的最宽可能的宽度稍大。

在此处输入图片说明

That way, your label will have enough space available for it to shifting without any change to the overall appearance of other elements that may have constraints connection with it.这样,您的标签将有足够的可用空间来进行移动,而不会改变可能与其有约束连接的其他元素的整体外观。

我最终使字体等宽

statusButton.font = NSFont(name: typeFace, size: 14)

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

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