由于某种原因,SwiftUi withAnimation 在 navigationBarItems 修饰符中不起作用。有解决办法吗?我知道视图上的 .animation 修饰符是动画作品,但这对于更复杂的动画来说是不够的。
我想知道以前没有人问过这个问题,我想更多的人有这个问题。有谁知道解决这个问题?
这里的一个例子:https ://drive.google.com/file/d/1d2Ud2xxhVCJBCfBQwlZ1mJgTnyNpxc_-/view?usp=sharing
struct TestView: View {
@State var red = true
var body: some View {
NavigationView {
VStack {
HStack {
Rectangle()
.fill(red ? Color.red : .blue)
.onTapGesture {
withAnimation(Animation.easeIn(duration: 1), {
red.toggle()
})
}
}
Spacer()
}
.navigationTitle("Test")
.navigationBarItems(leading:
HStack {
Rectangle()
.fill(red ? Color.red : .blue)
.onTapGesture {
withAnimation(Animation.easeIn(duration: 1), {
red.toggle()
})
}
}
)
}
}
}
struct TestView_Previews: PreviewProvider {
static var previews: some View {
TestView()
}
}
```
Edit: Aspires solution is valid for my original question. For some reason it still does not work in the context I am using it in:
struct ContentView: View {
@State var redColor = false
var body: some View {
NavigationView {
Button("change Color", action: {
withAnimation(Animation.easeIn(duration: 1), {
redColor.toggle()
})
})
.navigationTitle("Test")
.navigationBarItems(leading:
RectView(redColor: $redColor)
)
}
}
}
struct RectView: View {
@State var red: Bool = false
@Binding var redColor: Bool
var body: some View {
HStack {
Rectangle()
.fill(red ? Color.red : .blue)
}.onChange(of: redColor, perform: { _ in
red.toggle()
})
}
}