我有一个倒计时器。当数字不断变化时,文字会水平移动,感觉晃动太大了,因为我每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”)。小数点两边如何格式化?
您应该尝试使用每个字符间距相等的字体,通常称为等宽字体。
我找到了 2 种使用 SwiftUI 实现此目的的方法:
将Font的设计更改为等宽。这将影响文本的外观,因为它使用不同的字体设计。
.font(Font.system(size: 144, design: .monospaced).weight(.light))
另一种更好的方法是将当前的 Font 调整为等宽数字。你可以这样做:
.font(Font.monospacedDigit(Font.system(size: 144).weight(.light))())
从 iOS 15.0 开始可用
Text()
具有 monospacedDigit()
修饰符。
它保留了自己的字体设计和大小,只是解决了文本跳动的问题。
Text(timerText) // timerText is a string represents timer in the format "hh:mm:ss"
.monospacedDigit()