在SwiftUI中如何在没有状态变量的情况下为视图添加动画?

huangapple go评论50阅读模式
英文:

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 在SwiftUI中如何在没有状态变量的情况下为视图添加动画?

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
            }
        }
    }
}

huangapple
  • 本文由 发表于 2023年5月25日 23:42:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76334091.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定