【发布时间】:2020-03-21 19:46:36
【问题描述】:
我想让文本“Hello, World!”一旦视图出现,就会慢慢地上下浮动。
import SwiftUI
struct animate: View {
var body: some View {
Text("Hello, World!")
}
}
谢谢!
【问题讨论】:
标签: ios swift animation swiftui
我想让文本“Hello, World!”一旦视图出现,就会慢慢地上下浮动。
import SwiftUI
struct animate: View {
var body: some View {
Text("Hello, World!")
}
}
谢谢!
【问题讨论】:
标签: ios swift animation swiftui
这是可能的简单方法。使用 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()
}
}
}
【讨论】:
肯定有更好、更优雅的方法来解决它,但一种方法是:
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
}
}
}
}
}
【讨论】: