withAnimation

温馨提示:本文最后更新于2025-02-05 10:11:22,某些文章具有时效性,若有错误或已失效,请在下方留言

使用提供的动画重新计算视图主体,并返回结果。

struct ContentView: View {
    @State private var isActive = false

    var body: some View {
        VStack(alignment: isActive ? .trailing : .leading) {
            Circle().fill(isActive ? Color.red : Color.blue).frame(width: 50, height: 50)
            Button("Animate") {
                withAnimation(.linear) {
                    isActive.toggle()
                }
            }
            .frame(maxWidth: .infinity)
        }
    }
}

创建一个简单的弹跳动画

以下代码通过将偏移量设置为-40.0将表情符号向上移动。为了提供平滑的运动过渡,代码在有人点击表情符号后使用 withAnimation(_:_:) 函数应用弹性动画。

struct SimpleAnimationView: View {
    var emoji: String
    @State private var offset = 0.0

    var body: some View {
        EmojiView(emoji: emoji)
            .offset(y: offset)
            .onTapGesture {
                withAnimation(.bouncy) {
                    offset = -40.0
                }
            }
    }
}

例如,以下代码将偏移量设置为 -40.0以将表情符号向上移动,然后将偏移量设置为0.0以将表情符号返回到其原始位置:

struct SimpleAnimationView: View {
    var emoji: String
    @State private var offset = 0.0

    var body: some View {
        EmojiView(emoji: emoji)
            .offset(y: offset)
            .onTapGesture {
                withAnimation(.bouncy) {
                    offset = -40.0
                } completion: {
                    withAnimation {
                        offset = 0.0
                    }
                }
            }
    }
}

在下面的示例中,一个 Button 会改变一个 Text 视图的颜色和字体大小。由于这两个属性都应用于文本的路径,因此.interpolate 过渡可以通过整个过渡逐渐改变这些属性。

struct ContentTransitionView: View {
    @State private var color = Color.red
    @State private var currentFont = font1

    static let font1 = Font.system(size: 20)
    static let font2 = Font.system(size: 45)

    var body: some View {
        VStack {
            Text("Content transition")
                .foregroundColor(color)
                .font(currentFont)
                .contentTransition(.interpolate)
            Spacer()
            Button("Change") {
                withAnimation(Animation.easeInOut(duration: 5.0)) {
                    color = (color == .red) ? .green : .red
                    currentFont = (currentFont == ContentTransitionView.font1) ? ContentTransitionView.font2 : ContentTransitionView.font1
                }
            }
        }
    }
}
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容