简体   繁体   中英

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

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.

在此处输入图片说明

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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