Animate LinearGradient on state change in SwiftUI
Created Aug 23 2020
SWIFT1import SwiftUI23// Based on https://nerdyak.tech/development/2019/09/30/animating-gradients-swiftui.html45extension Color {6static func random()->Color {7let r = Double.random(in: 0 ... 1)8let g = Double.random(in: 0 ... 1)9let b = Double.random(in: 0 ... 1)10return Color(red: r, green: g, blue: b)11}12}1314struct ContentView: View {15@State private var gradientA: [Color] = [.red, .purple]16@State private var gradientB: [Color] = [.red, .purple]17@State private var selected = 018@State private var firstPlane: Bool = true1920func setGradient(gradient: [Color]) {21if firstPlane {22gradientB = gradient23}24else {25gradientA = gradient26}27firstPlane = !firstPlane28}293031var body: some View {32ZStack {3334Rectangle().fill(LinearGradient(gradient: Gradient(colors: self.gradientA), startPoint: .topLeading, endPoint: .bottomLeading)).edgesIgnoringSafeArea(.all)35Rectangle().fill(LinearGradient(gradient: Gradient(colors: self.gradientB), startPoint: .topLeading, endPoint: .bottomLeading)).edgesIgnoringSafeArea(.all)36.opacity(self.firstPlane ? 0 : 1)3738TabView(selection: $selected){39Text("☀️").font(.title).tag(0)40Text("🌦").font(.title).tag(1)41Text("⛈").font(.title).tag(2)42}.indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))43.tabViewStyle(PageTabViewStyle())44}.onChange(of: selected) { newselected in45print("\(newselected)!")46withAnimation (.easeInOut(duration: 0.7)){47self.setGradient(gradient: [Color.random(), Color.random()])48}49}50}51}5253struct ContentView_Previews: PreviewProvider {54static var previews: some View {55ContentView()56}57}