ios - 如何为时间间隔创建属性字符串,如 iOS 10 上的事件应用程序中所见的 3 小时 32 分钟?

标签 ios swift nsattributedstring nstimeinterval

<分区>

我正在尝试在我的 iOS 应用程序中将时间戳显示为属性字符串,就像我们可以在 iOS 10 上的 Apple Activity 应用程序(例如 sleep 分析)或 Fitbit sleep 跟踪中找到的那样。如下图所示,单位小于数字。

假设我有以秒为单位的时间间隔。

我考虑过使用 DateComponentsFormatter然后 localizedString(from:unitsStyle:)获取字符串。但是,我不知道如何将此字符串转换为单位更小且字体颜色不同的属性字符串。

我也考虑过使用 NSMeasurement + NSUnitDuration ,然后使用 NSMeasurementFormatter 将测量值转换为字符串.但是我遇到了同样的问题:如何将数字和字符分开。

当然,这应该适用于任何语言和区域设置。理想的可能是提取数字和单位,并对不同范围的数字和“纯”字符串应用不同的样式。知道如何解决这个问题吗?

enter image description here

最佳答案

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

关于ios - 如何为时间间隔创建属性字符串,如 iOS 10 上的事件应用程序中所见的 3 小时 32 分钟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39838249/

相关文章:

Swift - 在线程中执行SegueWithIdentifier

ios - 拆分属性字符串并保留格式

iphone - 我怎样才能换行 OHAttributedLabel

ios - MKAnnotionView 不显示标注

iOS Swift 3 WKWebView进度条不显示

ios - 使用 cocoapods 安装 GeoFire

swift - 将 mach 绝对时间戳转换为 NSDate

ios - 当我不注销就终止应用程序时,经过身份验证的用户是否保持登录状态?

ios - 防止在 NSAttributedString 中换行

ios - 如何以父 View 大小的百分比设置 View 的高度