在 SwiftUI 中,如果我将按钮添加到列表中,当集合更改时,列表将不再动画。我怎样才能让它动起来?
这是复制品。在代码的当前形式中,动画在列表被打乱时起作用。但是,如果我将
Text
替换为 Button
,则当我点击“随机播放”时,列表将不再显示动画。
struct ContentView: View {
@State private var fruits = ["apple", "banana", "cherry"]
var body: some View {
NavigationStack {
List(fruits, id: \.self) { fruit in
Text(fruit)
// Button(fruit) {} // Uncomment this line and comment the line above to reproduce the problem.
}
.toolbar {
Button("Shuffle") {
withAnimation { fruits = fruits.shuffled() }
}
}
}
}
}
列表中的默认按钮样式具有一些影响动画和交互的内置行为。
您应该添加修饰符 .buttonStyle(.plain) 来修复它
struct ContentView: View {
@State private var fruits = ["apple", "banana", "cherry"]
var body: some View {
NavigationStack {
List {
ForEach(fruits, id: \.self) { fruit in
Button(action: {}) {
Text(fruit)
.frame(maxWidth: .infinity, alignment: .leading)
}
.buttonStyle(.plain)
}
}
.toolbar {
Button("Shuffle") {
withAnimation {
fruits.shuffle()
}
}
}
}
}
}