Skip to content

Instantly share code, notes, and snippets.

@sergeytimoshin
Created November 27, 2020 09:55
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sergeytimoshin/1dc887d0f51b0d18f7bdcbf4bd21e181 to your computer and use it in GitHub Desktop.
Save sergeytimoshin/1dc887d0f51b0d18f7bdcbf4bd21e181 to your computer and use it in GitHub Desktop.
LinearGradient transition animation
import SwiftUI
extension Color {
static func random()->Color {
let r = Double.random(in: 0 ... 1)
let g = Double.random(in: 0 ... 1)
let b = Double.random(in: 0 ... 1)
return Color(red: r, green: g, blue: b)
}
}
struct ContentView: View {
@State private var gradientA: [Color] = [.red, .purple]
@State private var gradientB: [Color] = [.red, .purple]
@State private var firstPlane: Bool = true
func setGradient(gradient: [Color]) {
if firstPlane {
gradientB = gradient
}
else {
gradientA = gradient
}
firstPlane = !firstPlane
}
@State private var selected = 0
var body: some View {
ZStack {
LinearGradient(gradient: Gradient(colors: self.gradientA), startPoint: UnitPoint(x: 0, y: 0), endPoint: UnitPoint(x: 0, y: 1))
LinearGradient(gradient: Gradient(colors: self.gradientB), startPoint: UnitPoint(x: 0, y: 0), endPoint: UnitPoint(x: 0, y: 1))
.opacity(self.firstPlane ? 0 : 1)
TabView(selection: $selected) {
Text("☀️").font(.title).tag(0)
Text("🌦").font(.title).tag(1)
Text("⛈").font(.title).foregroundColor(Color.white).tag(2)
}
.indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))
.tabViewStyle(PageTabViewStyle())
.onChange(of: selected, perform: { value in
withAnimation(.spring()) {
self.setGradient(gradient: [Color.random(), Color.random()])
}
})
}
.edgesIgnoringSafeArea(.all)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment