某些类型的转换不起作用,其他类型起作用 - SwiftUI

Pra*_*ech 4 swiftui

我遇到一个问题,我试图对满足特定条件时出现的按钮使用转换。该按钮覆盖在另一个视图的顶部,并固定在底部。我想让它出现时从底部向上滑动,消失时向下滑动。

为此,我会使用.transition(.move(edge: .bottom).animation(.linear)). 然而,它根本不起作用——它只是弹出来,然后弹出来,没有任何滑动或动画。

.opacity.animation(.linear)更奇怪的是,当我使用或时,过渡确实有效.scale.animation(.linear),但不适用于任何其他过渡。

代码如下所示:

var body: some View {
    ScrollView {
        // ...
    }
    .overlay(alignment: .bottom) {
        if condition {
            Button(action: { /* ... */ }) {
                Text("Share")
            }
            .background { LinearGradient(...) }
            .clipShape(Capsule())
            .transition(.move(edge: .bottom).animation(.linear))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

知道为什么转换只能与.opacity和 一起使用.scale吗?我如何才能使其与 一起使用.move(edge: .bottom)

Asp*_*eri 5

将条件包装到容器中,因此有一个父级可以为其设置动画,例如

.overlay(alignment: .bottom) {
  VStack {                       // << here !!
    if condition {
        Button(action: { /* ... */ }) {
            Text("Share")
        }
        .background { LinearGradient(...) }
        .clipShape(Capsule())
        .transition(.move(edge: .bottom))
    }
  }
  .animation(.linear, value: condition)  // << important !!
}
Run Code Online (Sandbox Code Playgroud)

使用 Xcode 13.2 / iOS 15.2 进行测试