我注意到,当我为背景着色时,删除“视图”时将不会获得动画。
如果我删除Color(.orange).edgesIgnoringSafeArea(.all)
,则隐藏动画将起作用,否则Modal
将突然消失。有解决方案吗?
struct ContentView: View {
@State var show = false
func toggle() {
withAnimation {
show = true
}
}
var body: some View {
ZStack {
Color(.orange).edgesIgnoringSafeArea(.all)
Button(action: toggle) {
Text("Modal")
}
if show {
Modal(show: $show)
}
}
}
}
struct Modal: View {
@Binding var show: Bool
func toggle() {
withAnimation {
show = false
}
}
var body: some View {
ZStack {
Color(.systemGray4).edgesIgnoringSafeArea(.all)
Button(action: toggle) {
Text("Close")
}
}
}
}
答案 0 :(得分:0)
您需要使可移动的容器保存已删除的视图(这可以将动画保留在一个位置)。这是可能的解决方案。
通过Xcode 12 / iOS 14测试
struct ContentView: View {
@State var show = false
func toggle() {
show = true // animation not requried
}
var body: some View {
ZStack {
Color(.orange).edgesIgnoringSafeArea(.all)
Button(action: toggle) {
Text("Modal")
}
VStack { // << major changes
if show {
Modal(show: $show)
}
}.animation(.default) // << !!
}
}
}
struct Modal: View {
@Binding var show: Bool
func toggle() {
show = false // animation not requried
}
var body: some View {
ZStack {
Color(.systemGray4).edgesIgnoringSafeArea(.all)
Button(action: toggle) {
Text("Close")
}
}
}
}