当我按下按钮时,我希望第二个矩形(绿色)在第一个矩形(红色)上方上下移动
struct ContentView: View {
@State var visible = false
var body: some View {
return HStack {
Button("button") {
self.visible.toggle()
}
ZStack {
Rectangle()
.frame(width: 100, height: 100)
.foregroundColor(Color.red)
if visible {
Rectangle()
.frame(width: 100, height: 100)
.foregroundColor(Color.green)
.transition(.move(edge: .bottom))
.animation(.linear(duration: 2))
}
}
}
}
}
当绿色矩形出现时,它出现在红色矩形上方,但是当它消失时,移动的过渡出现在红色矩形后面。
答案 0 :(得分:5)
只需添加zIndex
:
struct ContentView: View {
@State var visible = false
var body: some View {
return HStack {
Button("button") {
self.visible.toggle()
}
ZStack {
Rectangle()
.frame(width: 100, height: 100)
.foregroundColor(Color.red)
if visible {
Rectangle()
.frame(width: 100, height: 100)
.foregroundColor(Color.green)
.transition(.move(edge: .bottom))
.animation(.linear(duration: 2))
.zIndex(1)
}
}
}
}
}