我编写了一个TimeInterval的扩展,它返回格式为"h m S"的字符串.例如,5小时33分15秒将被写为"5小时33分15秒".代码是这样的:

extension TimeInterval {
  init(hours: Int, minutes: Int, seconds: Int) {
    self = Double(hours * 3600 + minutes * 60 + seconds)
  }

  func toString() -> String {
    let totalSeconds = Int(self)
    let hours = totalSeconds / 3600
    let minutes = (totalSeconds % 3600) / 60
    let seconds = totalSeconds % 60

    if hours >= 1 {
      return "\(hours)h \(minutes)m"
    } else if minutes >= 1 {
      return "\(minutes)m \(seconds)s"
    } else {
      return "\(seconds)s"
    }
  }
}

我想用苹果的Duration.TimeFormatStyle时尚来实现同样的功能.例如,我可以执行以下操作:

let style = Duration.TimeFormatStyle(pattern: .hourMinuteSecond)
var formattedTime = Duration.seconds(someInterval).formatted(style)

我认为这是比编写一个toString()函数作为TimeInterval的扩展更好的做法,但我不确定如何创建这种样式.任何指导都是很棒的.

推荐答案

您正在寻找的是具有窄宽度的Duration UnitsFormatStyle个单元:

let duration: Duration = .seconds(15 + 33 * 60 + 5 * 3600)
let string = duration.formatted(.units(width: .narrow)) // "5h 33m 15s"

Swift相关问答推荐

防止NavigationLink自行返回导航视图

Form中的Divider在macOS上并不完全扩展

如何在visionOS中进行购买?&# 39;购买(选项:)在visionOS中不可用

如何在自定义视图中读取修改符子元素?

如何观察UIViewRepresentable中的多个变化?

关闭 SwiftUI TabView 中的子视图

在SwiftUI中使用ForEach循环来显示字典项的键和值在Form视图中

列表不显示信息

为什么 id 不能通过 struct 从 Objective-C 移植到 Swift?

如何使用带有 span 样式标签的 Swift XMLParser

如何在 SwiftUI 中用图像替换占位符文本?

Vapor 4 身份验证问题 [用户未通过身份验证]

Vapor - 流利的,将对象保存到 PostgreSQL

Xcode swift ui 错误KeyPathComparator仅在 macOS 12.0 或更高版本中可用

在 unwind segue 之后执行 push segue

UIButton 标题左对齐问题 (iOS/Swift)

TabView 在切换选项卡时重置导航堆栈

WKWebView 确实从本地文档文件夹加载资源

如何在 SwiftUI Segmented Picker 中更改选定的段 colored颜色

如何将应用程序与 iOS 联系人应用程序集成?