Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

swift - Can you animate a SwiftUI View on disappear?

I have a SwiftUI View which has a custom animation that runs onAppear. I am trying to get the view to animate onDisappear too but it just immediately vanishes.

The below example reproduces the problem - the MyText view should slide in from the left and slide out to the right. The id modifier is used to ensure a new view is rendered each time the value changes, and I have confirmed that both onAppear and onDisappear are indeed called each time, but the animation onDisappear never visibly runs. How can I achieve this?

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
          }
        }
    }
  }
}
question from:https://stackoverflow.com/questions/65831681/can-you-animate-a-swiftui-view-on-disappear

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Probably you wanted transition, something like

demo

struct Survey: View {
  @State private var id = 0

  var body: some View {
    VStack {
      MyText(text: $id)

      Button("Increment") {
        self.id += 1
      }
    }
  }

  struct MyText: View {
    @Binding var text: Int
    

    var body: some View {
      return Text("(text)").id(text)
            .frame(maxWidth: .infinity)
            .transition(.slide)
            .animation(.easeInOut(duration: 2))
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...