Animation in ScrollView is not working ? Using Xco

2020-07-24 05:51发布

问题:

I was trying to to do transition animation Scrollview but found out that how things work differently in scrollView. But still unable to do animation in it. I am providing code, please have a look. Using Xcode 11 beta 6

import SwiftUI 

struct ContentView : View {

@State private var isButtonVisible = false

var body: some View {

    NavigationView {
        ScrollView{
            VStack {
                Button(action: {
                 //   withAnimation {
                        self.isButtonVisible.toggle()
                  //   }
                }) {
                    Text("Press me")
                }

                if isButtonVisible {
                        Text("sss")

                            .frame(height: true ? 50 : 0, alignment: .center)
                              .background(Color.red)
                            .animation(.linear(duration: 2))
                      //  .transition(.move(edge: .top))

                }
            }

        }

    }


}}

回答1:

This must be a bug, and I suggest you file a bug report with Apple. I find a workaround (see code below), but it unfortunately uncovers another bug!

In order to make the animation inside the ScrollView to work, you can encapsulate the contents in a custom view. That will fix that problem.

This will uncover a new issue, which is made evident by the borders I added to your code: when the Text view is added, it shifts parts of the contents outside the ScrollView.

You will see that this is not correct. Try starting your app with a default value isButtonVisible = true, and you will see it renders it differently.

struct ContentView : View {
    var body: some View {
        NavigationView {
            ScrollView {
                EncapsulatedView().border(Color.green)
            }.border(Color.blue)
        }
    }
}

struct EncapsulatedView: View {
    @State private var isButtonVisible = false

    var body: some View {
        VStack {
            Text("Filler")
            Button(action: {
                withAnimation(.easeInOut(duration: 2.0)) {
                    self.isButtonVisible.toggle()
                }
            }) {
                Text("Press me")
            }

            if isButtonVisible {
                Text("sss")
                    .frame(height: true ? 50 : 0, alignment: .center)
                    .transition(.opacity)
                    .background(Color.red)
            }
            Spacer()
        }.border(Color.red)
    }
}