我正在尝试在我的 iOS 应用程序中将时间戳显示为属性字符串,就像我们可以在 iOS 10 上的 Apple Activity 应用程序(例如 sleep 分析)或 Fitbit sleep 跟踪中找到的那样。如下图所示,单位小于数字。
假设我有以秒为单位的时间间隔。
我考虑过使用 DateComponentsFormatter然后 localizedString(from:unitsStyle:)获取字符串。但是,我不知道如何将此字符串转换为单位更小且字体颜色不同的属性字符串。
我也考虑过使用 NSMeasurement + NSUnitDuration ,然后使用 NSMeasurementFormatter 将测量值转换为字符串.但是我遇到了同样的问题:如何将数字和字符分开。
当然,这应该适用于任何语言和区域设置。理想的可能是提取数字和单位,并对不同范围的数字和“纯”字符串应用不同的样式。知道如何解决这个问题吗?
UILabel 上有一个 .attributedText 属性。您需要像这样创建文本:
let hoursNumber = 6
let hoursUnit = "h"
let minutesNumber = 40
let minutesUnit = "m"
let numberFont = [ NSFontAttributeName: UIFont.systemFont(ofSize: 20) ]
let unitFont = [ NSFontAttributeName: UIFont.systemFont(ofSize: 14) ]
let timeString = NSMutableAttributedString(string: "\(hoursNumber)", attributes: numberFont)
timeString.append(NSAttributedString(string: hoursUnit, attributes: unitFont))
timeString.append(NSAttributedString(string: "\(minutesNumber)", attributes: numberFont))
timeString.append((NSAttributedString(string: minutesUnit, attributes: unitFont)))
然后设置你的timeLabel.attributedText = timeString
编辑
... 挑剔,挑剔 ;)
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute]
formatter.unitsStyle = .abbreviated
formatter.zeroFormattingBehavior = .pad
let unitFont = [NSFontAttributeName: UIFont.systemFont(ofSize: 14)]
let numberFont = [NSFontAttributeName: UIFont.systemFont(ofSize: 22)]
let time = formatter.string(from: 300)
let timeString = NSMutableAttributedString()
for letter in time!.unicodeScalars {
let timeLetter : NSAttributedString
if CharacterSet.decimalDigits.contains(letter) {
timeLetter = NSAttributedString(string: "\(letter)", attributes: numberFont)
} else {
timeLetter = NSAttributedString(string: "\(letter)", attributes: unitFont)
}
timeString.append(timeLetter)
}