0

I'm using UIBarButtonItem title part for a Clock. Every time the second changes the clock moves slightly left/right depending on the size of the character for the seconds part.

Is it possible to align the title text left or in some way so that the title stays fixed?

Top:

@IBOutlet weak var RefreshButton: UIBarButtonItem!

Under ViewDidLoad:

let font = UIFont.systemFont(ofSize: 14)
    RefreshButton.setTitleTextAttributes([NSAttributedString.Key.font: font], for: UIControl.State.normal)
    RefreshButton.tintColor = UIColor.black

Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ClockUTC), userInfo: nil, repeats: true)

Object:

@objc func ClockUTC(timer: Timer)
{

    let time = Date()
    let timeFormatter = DateFormatter()
    timeFormatter.dateFormat = "HH:mm:ss"
    timeFormatter.timeZone = TimeZone(abbreviation: "UTC")
    let stringDate = timeFormatter.string(from: time)
    RefreshButton.title = "UTC \(stringDate)"
}

Preview:

enter image description here

TylerP
  • 9,600
  • 4
  • 39
  • 43

2 Answers2

1

Try to set monospace font like this:

let font = UIFont.monospacedDigitSystemFont(ofSize: 14, weight: .bold)

if you want a regular, light or semibold font just change .bold in .semibold or .regular or .light

Fabio
  • 5,432
  • 4
  • 22
  • 24
  • Works nice and easy! –  Apr 28 '20 at 09:14
  • 1
    @PaulFerga I am happy to have been helpful :) – Fabio Apr 28 '20 at 09:16
  • I have encountered one more problem. The label freezes during scrolling in UIScrollView. Any idea how to fix that or should I post another thread for it? –  Apr 28 '20 at 22:50
  • 1
    convert your timer in a let constant: let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ClockUTC), userInfo: nil, repeats: true) after that add this line under: RunLoop.main.add(timer, forMode: RunLoop.Mode.common)... It should work – Fabio Apr 29 '20 at 07:01
0

I think you can try to use UIBarButtonItem with customView:

    let label = UILabel(frame: CGRect.zero)
    label.text = "10:20:44"
    label.textAlignment = .left
    label.sizeToFit()
    //If sizeToFit() not give you the right size, then you should calculate the size of the label based on the text.
    let button = UIBarButtonItem(customView: label)

About calculate label size you can try this link.

Thành Ngô Văn
  • 142
  • 3
  • 10