代码之家  ›  专栏  ›  技术社区  ›  James Allardice

你能在SwiftUI视图消失时设置动画吗?

  •  0
  • James Allardice  · 技术社区  · 4 年前

    我有一个SwiftUI View 其具有运行的自定义动画 onAppear 。我正试着把视图设置成动画 onDisappear 但它也会立即消失。

    下面的例子再现了这个问题—— MyText 视图应从左侧滑入,向右滑出。这个 id 修饰符用于确保每次值更改时都会呈现一个新视图,我已经确认了这两个 on附件 on消失 确实每次都被调用,但动画 on消失 从不明显奔跑。我怎样才能做到这一点?

    struct Survey: View {
      @State private var id = 0
    
      var body: some View {
        VStack {
          MyText(text: "\(id)").id(id)
    
          Button("Increment") {
            self.id += 1
          }
        }
      }
    
      struct MyText: View {
        @State private var offset: CGFloat = -100
        let text: String
    
        var body: some View {
          return Text(text)
            .offset(x: offset)
            .onAppear() {
              withAnimation(.easeInOut(duration: 2)) {
                self.offset = 0
              }
            }
            .onDisappear() {
              withAnimation(.easeInOut(duration: 2)) {
                self.offset = 100
              }
            }
        }
      }
    }
    
    0 回复  |  直到 4 年前
        1
  •  2
  •   Martijn Pieters    2 年前

    也许你想要过渡,比如

    demo

    更新: 用Xcode 13.4/iOS 15.5重新测试

    struct Survey: View {
        @State private var id = 0
    
        var body: some View {
            VStack {
                MyText(text: "\(id)")
    
                Button("Increment") {
                    self.id += 1
                }
            }
        }
    
        struct MyText: View {
            var text: String
    
    
            var body: some View {
                Text("\(text)").id(text)
                    .frame(maxWidth: .infinity)
                    .transition(.slide)
                    .animation(.easeInOut(duration: 2), value: text)
            }
        }
    }
    
        2
  •  0
  •   Moose    4 年前

    恐怕它无法工作,因为一旦视图被隐藏,.onEdisappear修饰符就会被调用。 然而,这里有一个很好的答案: Is there a SwiftUI equivalent for viewWillDisappear(_:) or detect when a view is about to be removed?