简体   繁体   中英

SwiftUI animation within ScrollView not working

Just can't get my head around this. I have a simple animation which works perfectly. But when I wrap the view into a ScrollView (by uncommenting the 2 lines) it does not animate anymore? Anybody a clue?

import SwiftUI

struct ContentView: View {
    @State var offset = CGSize(width: 0, height: 0)

    var body: some View {
//      ScrollView {
            VStack(spacing: 50) {
                Rectangle()
                    .frame(width: 100, height: 100)
                    .offset(self.offset)
                Button(action: {
                    withAnimation {
                        self.offset.width += 66
                    }
                })
                {
                    Text("Animate me")
                }
            }.frame(width: 300)
//      }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

I've already noticed this behaviour. The issue seems to be the explicit animation. If you go for an implicit animation it works:

struct ContentView: View {
    @State var offset = CGSize(width: 0, height: 0)

    var body: some View {
      ScrollView {
            VStack(spacing: 50) {
                Rectangle()
                    .frame(width: 100, height: 100)
                    .offset(self.offset)
                    .animation(.linear)
                Button(action: {
                    self.offset.width += 66
                })
                {
                    Text("Animate me")
                }
            }.frame(width: 300)
      }
    }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}

I haven't managed to get the reason yet, so consider this as a workaround. It may be a SwiftUI bug or something I still can't understand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM