我正在使用UIBarButtonItem
标题部分作为时钟。每次秒变化时,时钟会根据秒部分的字符大小向左/向右稍微移动。
是否可以使标题文本左对齐或以某种方式使标题保持固定?
顶部:
@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)
对象:
@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)"
}
预览:
尝试像这样设置等宽字体:
let font = UIFont.monospacedDigitSystemFont(ofSize: 14, weight: .bold)
如果要使用常规,浅色或半粗体字体,只需将.bemi更改为.semibold或.regular或.light
我认为您可以尝试将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。