简体   繁体   English

SwiftUI 基础动画

[英]SwiftUI basic animation

Let's say I have a number and I want to animate the transition each time it changes its value.假设我有一个数字,我想在每次更改其值时为过渡设置动画。 So the value disappears to the left and the new increased value appears from the right.因此该值在左侧消失,而新增加的值从右侧出现。 Can this easily be made using .transition(.slide) ?这可以使用.transition(.slide)轻松实现吗?

struct ContentView: View {
    @StateObject var viewModel = ViewModel()

    var body: some View {
        VStack(spacing: 64) {
            Text(viewModel.count.description)
                .font(.largeTitle)
            Button("Increment", action: viewModel.increment)
        }
    }
}

final class ViewModel: ObservableObject {
    @Published var count = 0

    func increment() {
        count += 1
    }
}

The .slide transition by default inserts from left and removes to right. .slide过渡默认从左侧插入并从右侧移除。 We can use asymmetric move transition to achieve your goal.我们可以使用非对称移动过渡来实现您的目标。

Here is a raw demo of possible approach.这是可能的方法的原始演示。 Tested with Xcode 13 / iOS 15.使用 Xcode 13 / iOS 15 测试。

演示

struct ContentView: View {
    @StateObject var viewModel = ViewModel()

    var body: some View {
        VStack(spacing: 64) {
            // transition works on view insertion/remove that is
            // why we conditionally switch views
            if 1 == viewModel.count % 2 {
                NumberView(number: viewModel.count)
            } else {
                NumberView(number: viewModel.count)
            }
            Button("Increment", action: viewModel.increment)
        }
        .animation(.default, value: viewModel.count)
    }
}

// By default on transition view is removed to the edge from
// which it appears, that is why we need asymmetric transition
struct NumberView: View {
    let number: Int
    var body: some View {
        Text("\(number)")
            .font(.largeTitle)
            .frame(maxWidth: .infinity)
            .transition(.asymmetric(insertion: .move(edge: .trailing), removal: .move(edge: .leading)))
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM