有没有办法在显示计时器时防止 SwiftUI 文本标签稍微移动?

M.S*_*rag 3 swift swiftui

我有一个简单的HStack包含 2 个Text显示计时器的结构。当定时器值改变时,它会不断改变位置。有没有办法避免这种行为。

struct DurationLabel: View {
    let majorDuration: String // the hours/minutes part "00:00"
    let minorDuration: String // the seconds part "00"

    var body: some View {
        HStack(spacing: 0) {
            Text(majorDuration + minorDuration)
                .font(.system(size: 90))
            Text(minorDuration)
                .font(.body)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

演示 GIF

Ger*_*eon 11

对于这样的显示,我更喜欢使用等宽数字的字体。你可以像这样在你的文本中使用它们:

Text("your Text here").font(Font.largeTitle.monospacedDigit())
Run Code Online (Sandbox Code Playgroud)


ars*_*ius 6

我已经为音频播放器等做过很多次了......如果你想保持相同的字体,你可以这样做:

ZStack(alignment: .leading) {
  Text("00:00").opacity(0.0)
  Text("MM:SS") // Put your actual numbers in here with the same formatting.
}
Run Code Online (Sandbox Code Playgroud)

ZStack自身大小将基于最大的子视图,并且0基本上是所有字体中最宽的数字。

通过.center对齐,这将防止周围的视图每秒发生变化。使用.leading,您可以防止标签本身发生太大变化。

此技术适用于任何可能改变大小的内容类型。只需加载具有最大可能版本的“虚拟”视图并将其隐藏即可。然后将您的真实内容保留在可见视图中。然后你可以避免硬编码帧大小等......