我正在开发一个自定义进度条.我有一个文本,我想在动画 timeshift 动一个进度.而是文本消失并重新出现在新的位置(见下面的gif).
代码:
private struct MyProgressBar: View {
let progress: Double
var body: some View {
RoundedRectangle(cornerRadius: 5)
.frame(height: 20)
.foregroundColor(.gray)
.overlay(alignment: .leading) {
GeometryReader { geo in
let progressWidth = geo.size.width * progress
RoundedRectangle(cornerRadius: 5)
.foregroundColor(.yellow)
.frame(width: progressWidth)
.overlay(alignment: .topTrailing) {
bubble(progress)
.fixedSize()
.alignmentGuide(HorizontalAlignment.trailing) { d in
d[HorizontalAlignment.center]
}
.alignmentGuide(VerticalAlignment.top) { d in
d[.bottom]
}
}
}
}
.padding()
}
@ViewBuilder
private func bubble(_ progress: Double) -> some View {
Text(progress.formatted(.percent))
.monospacedDigit()
.padding(5.0)
.background {
RoundedRectangle(cornerRadius: 2)
.foregroundColor(.green)
}
}
}
struct MyProgressBarExample: View {
@State private var progress: Double = 0.3
var body: some View {
VStack {
MyProgressBar(progress: progress)
VStack {
Button("change") {
withAnimation() {
progress = Double.random(in: 0.0...1.0)
}
}
Slider(
value: $progress.animation(),
in: 0.0...1.0,
step: 0.005
)
.padding()
}
}
}
}
使用动态值时,文本会消失并重新出现,但如果我将文本更改为某个常量字符串,如"Hello",则文本移动得很好.
如何让绿色背景的文字移动,而不是出现和消失?