swiftui - SwiftUI:带动画条的步进器
问题描述
我想创建一个带有动画条的步进器组件。这是我得到的结果:
这个想法是该条应始终居中,并且我想在值更改时为蓝色条设置动画,但我无法使其正常工作。
这是我的代码:
struct Stepper: View {
@Binding var currentIndex: Int
var total: Int
var body: some View {
ZStack(alignment: .center) {
ZStack(alignment: .leading) {
Color.gray.opacity(0.4)
Color.blue
.frame(width: 175.5 / CGFloat(total) * CGFloat(currentIndex))
}
.frame(width: 175.5, height: 2)
Text("\(currentIndex)")
.foregroundColor(.black)
.offset(x: -113)
Text("\(total)")
.foregroundColor(.black)
.offset(x: 113)
}
.frame(width: .infinity, height: 18)
}
init(withTotal total: Int,
andCurrentIndex currentIndex: Binding<Int>) {
self._currentIndex = currentIndex
self.total = total
}
func update(to value: Int) {
guard value >= 0, value <= total else {
return
}
withAnimation {
currentIndex = value
}
}
}
以及我如何在容器视图中调用它:
struct StepperVC: View {
@State private var currentIndex: Int = 1
var body: some View {
VStack(spacing: 32) {
Stepper(withTotal: 8, andCurrentIndex: $currentIndex)
Button(action: {
currentIndex += 1
}, label: {
Text("INCREMENT")
})
Button(action: {
currentIndex -= 1
}, label: {
Text("DECREMENT")
})
}
}
}
你能帮我理解为什么动画不起作用吗?另外,有没有更好的方式来布局 UI?
谢谢!
解决方案
currentIndex
最简单的解决方案是像这样在withAnimation
块中进行更改:
Button(action: {
withAnimation {
currentIndex += 1
}
}, label: {
Text("INCREMENT")
})
推荐阅读
- c++ - 为什么允许某些非常量表达式作为 constexpr 逗号运算符的操作数?
- python - Python 矩阵除法
- sql-server - SQL Server:具有相同选择查询的视图和 SQL 编辑器中的执行时间不同
- java - WeakHashMap 的实际用途是什么?
- serverless - 使用无服务器在 lambda 上部署代码失败
- javascript - 尝试在 javascript 中访问全局变量方法,但仅在特定时间有效
- matlab - 我怎样才能最好地代表重质材料的减速带?
- javascript - 不匹配类型:对象而不是用户(已创建)
- swift - 我可以将按钮放到单独的视图中吗?
- sql - 在返回多个表的表中的每一列上选择不同的