如何删除具有不同过渡的视图背景? SwiftUI

问题描述 投票:0回答:1

我将提供一个简化的示例。假设当我切换时,我想立即删除文本的背景,而不需要任何过渡或动画,但让文本本身以不透明度淡出。我怎样才能实现这个目标?请不要建议使用

ZStack
代替
.background
;我正在寻找这种特定情况下的解决方案。如果不可能,请告诉我。

struct BackgroundTransition: View {

    @State var show = true
    
    var body: some View {
        VStack {
    
            Group {
                if show {
                    Text("Some Text")
                        .background(
                            Color.blue
                                .transition(.identity)
                                .animation(.none, value: show)
                        )
    
                } else {
                    Spacer()
                        .frame(maxHeight: .infinity)
                }
            }
            .frame(height: 50)
    
            Button("Toggle") {
                withAnimation {
                    show.toggle()
                }
            }
    
        }
    }

}


 I tried applying `.identity` transition to the background view and `.none` animation, but it didn't work.
swift swiftui transition
1个回答
0
投票

我能想到的唯一方法是拥有两个独立的变量:一个是动画的,另一个不是。

struct BackgroundTransition: View {

    @State var show = true
    @State var showBackground = true
    
    var body: some View {
        VStack {
            
            Group {
                
                Text("Some Text")
                    .opacity(show ? 1 : 0)
                    .background {
                        if showBackground {
                            Color.blue
                                .transition(.identity)
                        }
                    }
                
                if !showBackground {
                    Spacer()
                        .frame(maxHeight: .infinity)
                }
                
            }
            .frame(height: 50)
    
            Button("Toggle") {
                withAnimation {
                    show.toggle()
                }
                /// Do not animate this
                showBackground.toggle()
            }
    
        }
    }

}

为了做到这一点,我删除了 if ,否则无论任何其他条件如何,里面的所有视图都会被动画化。 但我不知道如何处理这种情况下的垫片,因为一旦点击切换按钮,它就会推动视图。 无论如何尝试一下,让我知道你的想法!

© www.soinside.com 2019 - 2024. All rights reserved.