在SwiftUI中对T的动画进行隐藏和显示

时间:2020-03-18 12:40:42

标签: ios swift swiftui

enter image description here enter image description here enter image description here

点击Toggle Text时,它必须隐藏或显示收藏夹 Text,并带有淡入淡出动画和延迟
或在屏幕上显示文本时给我一些动画。 我尝试了几种“动画”方式,但到目前为止还无法正常工作。这是代码。

struct ContentView: View {

    @State var showText: Bool
    var body: some View {
        VStack() {
            Spacer()
            Image(systemName: "star.fill")

            if self.showText {
                // Changing selection value.
                    Text("Favorites")
                        .font(.custom("Helvetica Neue", size: 20))
                        .animation(Animation.easeOut(duration: 2.0).delay(0.5))
            }

            Spacer()
                .frame(height: 50)

            Button(action: {
                self.showText.toggle()
            }) {
                Text("Toggle Text")
            }
            Spacer()
        }
        .padding(5)
        .font(.custom("Helvetica Neue", size: 14))
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(showText: false)
    }
}

1 个答案:

答案 0 :(得分:1)

这是可行的方法(经过测试并与Xcode 11.2 / iOS 13.2配合使用)

注意:预览在处理过渡时效果不好,因此请使用模拟器或真实设备进行测试。

struct ContentView: View {

    @State var showText: Bool = false
    var body: some View {
        VStack() {
            Spacer()
            Image(systemName: "star.fill")

            if self.showText {
                // Changing selection value.
                Text("Favorites")
                    .font(.custom("Helvetica Neue", size: 20))
                    .transition(.opacity)  // << transition works in add/remove view
            }

            Spacer()
                .frame(height: 50)

            Button(action: {
                withAnimation(Animation.easeOut(duration: 2.0).delay(0.5)) {
                    self.showText.toggle() // << transition requires explicit animation
                }
            }) {
                Text("Toggle Text")
            }
            Spacer()
        }
        .padding(5)
        .font(.custom("Helvetica Neue", size: 14))
    }
}