iosswiftuibarbuttonitemuibarbuttonitemstyle

UIBarButtonItem Tittle text alignment


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


Solution

  • 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