0

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://i.stack.imgur.com/xowHs.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?

Leon
  • 361
  • 3
  • 8

2 Answers2

0

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, i.e 99:99:99.9 in your case, the see how much the value of the label width.

enter image description here

Then set the width constraint for your label.

enter image description here

And finally set constraint value need to be slightly larger than the widest possible width that you have seen at the first step.

enter image description here

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.

yogipriyo
  • 636
  • 8
  • 13
  • Thank you so much for your reply. I followed your advice and set a fixed width let statusBarItem: NSStatusItem = NSStatusBar.system.statusItem(withLength: 200) Unfortunately, the text is still shifting. Here's an example https://imgur.com/DusVIpr.gif – Leon Feb 06 '20 at 16:00
  • I see. Then how about set the label to be left aligned as well? The constraint above will help to solve the space related issue while the text alignment may be able help to fix the left side position of the label. @Leon – yogipriyo Feb 07 '20 at 03:36
0

I ended up making the font monospaced

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

Leon
  • 361
  • 3
  • 8