如何更新此自定义选择器动画并过渡到 iOS 15?

How can I update this custom Picker animation and transition to iOS 15?

下面的代码在 iOS 15 之前运行良好,但现在我收到警告 'animation' was deprecated in iOS 15.0: Use withAnimation or animation(_:value:) instead.

环顾四周,看来我应该使用 .animation(_, value: someValue) - 这确实消除了警告,但随后代码无法正确设置动画。我想这与选择器太快有关?或者选择器影响 id 的视图?

这是有效的代码,但当然,我更愿意使用 iOS 15:

使其保持最新

struct SamplePickerSwap: View {
    let swapAnimation: Animation = .easeInOut(duration: 0.3333)
    let swapRight: AnyTransition = .asymmetric(
        insertion: .move(edge: .trailing),
        removal: .move(edge: .leading))
    let swapLeft: AnyTransition = .asymmetric(
        insertion: .move(edge: .leading),
        removal: .move(edge: .trailing))
    
    @State private var picker = 0
    @State private var segments = ["Left", "Right"]
    var body: some View {
        
        VStack {
            Picker("", selection: $picker) {
                ForEach(0 ..< segments.count) { index in
                    Text(self.segments[index])
                        .tag(index)
                }
            }
            .pickerStyle(SegmentedPickerStyle())
            
            switch picker {
                case 0:
                    Rectangle().fill(Color.green)
                        //.animation(swapAnimation, value: page) //This does not work
                        .animation(swapAnimation) // This is deprecated...
                        .transition(swapLeft)
                case 1:
                    Rectangle().fill(Color.yellow)
                        .animation(swapAnimation)
                        .transition(swapRight)
                default:
                    Rectangle().fill(Color.green)
                        .animation(swapAnimation) //
                        .transition(swapLeft)
            }
            Spacer()
        }
        .padding()
    }
}


我试过添加另一个变量 @State private var page = 0 并用这个改变它:

            .onChange(of: picker, perform:  { _ in
                page = picker
            })

并使用 .animation(swapAnimation, value: page).animation(swapAnimation, value: picker) 的 iOS 动画代码,但似乎没有任何组合起作用。

我们需要向容器添加动画(VStack 在本例中)以使子视图具有动画效果,例如

    VStack {
        Picker("", selection: $picker) {
            ForEach(0 ..< segments.count) { index in
                Text(self.segments[index])
                    .tag(index)
            }
        }
        .pickerStyle(SegmentedPickerStyle())

        switch picker {
        case 0:
            Rectangle().fill(Color.green)
                .transition(swapLeft)
        case 1:
            Rectangle().fill(Color.yellow)
                .transition(swapRight)
        default:
            Rectangle().fill(Color.green)
                .transition(swapLeft)
        }
        Spacer()
    }
    .animation(swapAnimation, value: picker) // << here !!

测试 Xcode 13 / iOS 15