在swiftUI中创建滑动文字动画

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

我正在尝试在 swiftUI 中为一些数字文本设置动画。但还没有找到想要的结果!为了更容易理解,请看下图...

到目前为止,这是我的代码:

struct AnimatedText: View {
    
  @State var showingText = "234"
  
  var body: some View {
    VStack {
        
        HStack {
            Spacer()
            Text(showingText)
                .font(.title)
                .transition(.slide)

        }.padding(20)
        
      Button("Add Number") {
          withAnimation(.spring()) {
              showingText += String(Int.random(in: 0..<9))
          }
         
      }
    }
  }
}

swift animation swiftui
1个回答
0
投票

一种方法是将每个角色分成自己的

Text
视图。然后
.push(from: .trailing)
的转变达到了预期的结果:

@State var showingText = "234"

var body: some View {
    VStack {
        HStack(spacing: 0) {
            Spacer()
            let charArray = Array(showingText)
            ForEach(charArray.indices, id: \.self) { i in
                let char = String(charArray[i])
                Text(char)
                    .transition(.push(from: .trailing))
                
            }
            
        }.padding(20)
        
        Button("Add Number") {
            withAnimation(.spring()) {
                showingText += String(Int.random(in: 0..<9))
            }
            
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.