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

Ril*_*eux 2 transition deprecation-warning ios-animations swiftui

下面的代码在 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()
    }
}


Run Code Online (Sandbox Code Playgroud)

我尝试添加另一个变量@State private var page = 0并用以下命令更改它:

            .onChange(of: picker, perform:  { _ in
                page = picker
            })
Run Code Online (Sandbox Code Playgroud)

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

Asp*_*eri 8

我们需要向容器添加动画(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 !!
Run Code Online (Sandbox Code Playgroud)

使用 Xcode 13 / iOS 15 进行测试

演示