英文:
Animate a view in SwiftUI without a state-variable?
问题
我正在学习SwiftUI,目前已经涉及到动画,但似乎只能通过某种用户交互来触发状态变化才能实现动画。在视图加载时是否可以播放循环动画?我想要将一些字母(Image-views或Text-views)作为设计的一部分以上下跳动的方式进行动画。在原生SwiftUI中是否可以实现这一点,而不需要使用可能在苹果更新框架时停止工作的各种技巧?
我也在研究Rive,但我真的希望能够直接在SwiftUI中实现这一点。
英文:
I’m learning SwiftUI right now and have gotten to animations, which so far only seem to work with a state-change by some kind of user interaction.
Is it possible to have a looping animation playing as soon as the view loads? I want to animate some letters bouncing up and down (Image-views or Text-views) as a part of the design. Is this possible with native SwiftUI without different hacks that might stop working when Apple updates the framework?
I’ve also been looking at Rive, but I really wish it would be possible to do directly in SwiftUI.
答案1
得分: 1
结构 ContentView: View {
@State private var animate = false
var body: some View {
HStack {
Text("上")
.offset(y: animate ? -20 : +20)
Text("和")
.offset(y: animate ? +20 : -20)
Text("下")
.offset(y: animate ? -20 : +20)
Text("再次")
.offset(y: animate ? +20 : -20)
}
.onAppear {
withAnimation(.easeInOut.repeatForever(autoreverses: true)) {
animate = true
}
}
}
}
英文:
Following @HunterLion, Just for the fun of it
struct ContentView: View {
@State private var animate = false
var body: some View {
HStack {
Text("Up")
.offset(y: animate ? -20 : +20)
Text("and")
.offset(y: animate ? +20 : -20)
Text("Down")
.offset(y: animate ? -20 : +20)
Text("again")
.offset(y: animate ? +20 : -20)
}
.onAppear {
withAnimation(.easeInOut.repeatForever(autoreverses: true)) {
animate = true
}
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论