我正在尝试在 ZStack 中创建多个转换。
这是一个测试 View ,其中包含一些文本和一个圆圈,它们都有自己的过渡效果。
struct Test: View {
@Binding var isPresented: Bool
@State private var showCircle: Bool = false
@State private var showRect: Bool = false
var body: some View {
ZStack {
if showRect {
VStack {
Text("Hello World")
.foregroundColor(.white)
.padding()
}
.background(Color.green)
.transition(.move(edge: .bottom))
}
if showCircle {
Circle()
.fill(Color.purple)
.transition(.slide)
}
}
.onAppear() {
withAnimation {
self.showRect.toggle()
self.showCircle.toggle()
}
}
.onDisappear() {
withAnimation {
self.showCircle.toggle()
self.showRect.toggle()
}
}
}
}
我这样添加这个 View :
struct ContentView: View {
@State private var toggler: Bool = false
var body: some View {
ZStack {
if toggler {
Test(isPresented: $toggler)
}
Button("Show/Hide") {
withAnimation {
self.toggler.toggle()
}
}
}
}
}
过渡作用于出现。
但是 onDisappear 似乎是在移除期间而不是之前被调用的。
如何重置状态变量以触发移除时的转换或者我应该使用什么其他方法?
其他尝试:
我还尝试创建自定义修饰符以将它们与 Anytransition.modifier 一起使用 - 但失败了,因为我无法进行类型转换以访问 State 变量,而 Anytransition.modifier 要求修饰符符合 ViewModifier。
TestView 中的 dismiss 函数如果我想从其自身中解散 View 但显然不会在它被其父级解散时起作用。
最佳答案
这样做,而不是 onAppear/disappear
struct ContentView : View {
@State private var isButtonVisible = true
var body: some View {
VStack {
Toggle(isOn: $isButtonVisible.animation()) {
Text("Show/Hide button")
}
if isButtonVisible {
Button(action: {}) {
Text("Hidden Button")
}.transition(.move(edge: .trailing))
}
}
}
}
或者用按钮
struct ContentView : View {
@State private var isButtonVisible = true
var body: some View {
VStack {
Button(action: {
withAnimation {
self.isButtonVisible.toggle()
}
}) {
Text("Press me")
}
if isButtonVisible {
Button(action: {}) {
Text("Hidden Button")
}.transition(.move(edge: .trailing))
}
}
}
}
您还可以组合转换:查看:https://swiftwithmajid.com/2019/06/26/animations-in-swiftui/
关于swift - 如何在 ZStack 中创建多个转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58797449/