UIBarButtonItem 标题文本对齐

UIBarButtonItem Tittle text alignment

我正在使用 UIBarButtonItem 时钟的标题部分。每次秒更改时,时钟都会根据秒部分的字符大小稍微移动 left/right。

是否可以将标题文本左对齐或以某种方式使标题保持固定?

顶部:

@IBOutlet weak var RefreshButton: UIBarButtonItem!

在 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)"
}

预览:

我想你可以尝试将 UIBarButtonItem 与 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)

关于计算标签大小你可以试试这个link

尝试像这样设置等宽字体:

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

如果您想要常规、浅色或半粗体字体,只需将 .bold 更改为 .semibold 或 .regular 或 .light