鉴于以下视图,当
showFavoriteFlag
从外部设置为 false
时,最喜欢的标志会消失 - 但该更改不是动画的。为什么不?我希望文本“测试”向右滑动,但相反,一旦最喜欢的标志消失,它就会立即出现在那里。
struct HeaderComponent: View {
let timestamp: Date
@Binding var showFavoriteFlag: Bool
var body: some View {
HStack {
TimestampComponent(for: timestamp)
Spacer(minLength: 0)
Text("Test")
if showFavoriteFlag {
FavoriteFlagComponent()
}
}
.animation(.default, value: showFavoriteFlag)
}
}
更新回复:请求的 MRE - 这是(简化的)我在应用程序中使用该组件的方式。问题似乎与
ForEach
有关,因为动画按预期适用于第一个标头组件,但不适用于两个嵌入的标头组件:
import SwiftUI
struct HeaderComponent: View {
@Binding var showFavoriteFlag: Bool
var body: some View {
HStack {
Text("Timestamp")
Spacer(minLength: 0)
Text("Test")
if showFavoriteFlag {
Text("Favorite")
}
}
.animation(.default, value: showFavoriteFlag)
}
}
class Model: ObservableObject {
@Published var flags: [Bool] = [true, false]
@Published var otherCondition: Int = 1
func toggle() {
for index in 0..<flags.count {
flags[index].toggle()
}
}
}
struct ContentView: View {
@ObservedObject var model = Model()
var body: some View {
VStack {
HeaderComponent(showFavoriteFlag: Binding.constant(model.otherCondition == 0 ? false : model.flags[0]))
ForEach(model.flags, id: \.self) { flag in
HeaderComponent(showFavoriteFlag: Binding.constant(model.otherCondition == 0 ? false : flag))
}
Button(action: { model.toggle() }, label: { Text("Toggle") })
}
}
}
#Preview {
ContentView()
}
行
.animation(.default, value: showFavoriteFlag)
单独应用淡入淡出动画,以创建幻灯片过渡:
FavoriteFlagComponent
添加过渡:FavoriteFlagComponent()
.transition(.slide)
.animation(.default, value: showFavoriteFlag)
行,也可以在更改withAnimation
的值时添加
showFavoriteFlag