繁体   English   中英

在 SwiftUI 中动画隐藏和显示 T

[英]Animate hide and show of T in SwiftUI

在此处输入图片说明 在此处输入图片说明 在此处输入图片说明

当我点击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)
    }
}

这是可能的方法(已测试并适用于 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))
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM