【问题标题】:How to make a simple up and down floating animation in SwitfUI?如何在 SwiftUI 中制作简单的上下浮动动画?
【发布时间】:2020-03-21 19:46:36
【问题描述】:

我想让文本“Hello, World!”一旦视图出现,就会慢慢地上下浮动。

import SwiftUI

struct animate: View {
    var body: some View {
        Text("Hello, World!")
    }
}

谢谢!

【问题讨论】:

    标签: ios swift animation swiftui


    【解决方案1】:

    这是可能的简单方法。使用 Xcode 11.4 / iOS 13.4 测试。当然可以根据需要调整参数。

    struct BoncingView: View {
        @State private var bouncing = false
        var body: some View {
            Text("Hello, World!")
                .frame(maxHeight: .infinity, alignment: bouncing ? .bottom : .top)
                .animation(Animation.easeInOut(duration: 5.0).repeatForever(autoreverses: true))
                .onAppear {
                    self.bouncing.toggle()
                }
        }
    }
    

    【讨论】:

    • 我喜欢这个解决方案??
    【解决方案2】:

    肯定有更好、更优雅的方法来解决它,但一种方法是:

    struct ContentView: View {
    
    
        @State var y : CGFloat = 100
        @State var addThis: CGFloat = 100
    
    
        var body: some View {
            Text("Hello, World!")
                .position(x: 100, y: y)
                .onAppear() {
                    Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (timer) in
                        withAnimation() {
                            self.addThis = -self.addThis
                            self.y = self.y + self.addThis
                        }
                    }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      相关资源
      最近更新 更多