如何防止数值变化时文本晃动并格式化小数点两边双精度值?

问题描述 投票:0回答:3

我有一个倒计时器。当数字不断变化时,文字会水平移动,感觉晃动太大了,因为我每0.1秒更新一次计时器。

如何防止文字晃动?这是完整代码:

struct CountDownTimerView: View {
    
    @ObservedObject var timer = CountdownTimer(seconds: 15)
    
    var body: some View {
        Text(String(format: "%.1f", timer.time))
            .font(Font.system(size: 144).weight(.light))
    }
}

class CountdownTimer: ObservableObject {
    @Published var time: Double
    
    /// time interval in seconds
    let interval = 0.1
    
    lazy var timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { _ in
        self.update()
    }
    
    init(seconds: Double) {
        time = seconds
        timer.fire()
    }
    
    func update() {
        if self.time-interval <= 0 {
            self.time = 0
            timer.invalidate()
        } else {
            self.time -= interval
        }
    }
}

我想将双精度值 7.329523 的时间显示为 07.3。我可以使用

String(format: "%02d", Int(timer.time))
实现小数点之前的格式(例如“07”),或者使用
(String(format: "%.1f", timer.time)
实现小数点之后的格式(例如“7.3”)。小数点两边如何格式化?

swift timer swiftui double
3个回答
7
投票

您应该尝试使用每个字符间距相等的字体,通常称为等宽字体。

我找到了 2 种使用 SwiftUI 实现此目的的方法:

等宽字体

Font的设计更改为等宽。这将影响文本的外观,因为它使用不同的字体设计。

.font(Font.system(size: 144, design: .monospaced).weight(.light))

自适应字体

另一种更好的方法是将当前的 Font 调整为等宽数字。你可以这样做:

.font(Font.monospacedDigit(Font.system(size: 144).weight(.light))())


1
投票

就是这样(您必须在 0 之前给出输出的全宽度,因此 [0 7 . 3] 是四个字符,因此:

let value: CGFloat = 7.329523
Text(String(format: "%04.1f", value))

输出

使用 Xcode 12 进行测试


0
投票

从 iOS 15.0 开始可用

Text()
具有
monospacedDigit()
修饰符。

它保留了自己的字体设计和大小,只是解决了文本跳动的问题。

            Text(timerText) // timerText is a string represents timer in the format "hh:mm:ss"
                .monospacedDigit()
© www.soinside.com 2019 - 2024. All rights reserved.