Skip to content

Commit

Permalink
"docs(snippet): Add new snippet 2020-8-23-animatelineargradientonstat…
Browse files Browse the repository at this point in the history
…echangeinswiftui.mdx"
  • Loading branch information
MaximeHeckel committed Aug 23, 2020
1 parent ba10825 commit b81947f
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions snippets/2020-8-23-animatelineargradientonstatechangeinswiftui.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
---
title: Animate LinearGradient on state change in SwiftUI
language: swift
created: 2020-08-23T22:32:22.126Z
slug: 2020-8-23-animatelineargradientonstatechangeinswiftui
snippetImage: './img/2020-8-23-animatelineargradientonstatechangeinswiftui.png'
type: snippet
---

```swift snippet
import SwiftUI

// Based on https://nerdyak.tech/development/2019/09/30/animating-gradients-swiftui.html

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 selected = 0
@State private var firstPlane: Bool = true

func setGradient(gradient: [Color]) {
if firstPlane {
gradientB = gradient
}
else {
gradientA = gradient
}
firstPlane = !firstPlane
}


var body: some View {
ZStack {

Rectangle().fill(LinearGradient(gradient: Gradient(colors: self.gradientA), startPoint: .topLeading, endPoint: .bottomLeading)).edgesIgnoringSafeArea(.all)
Rectangle().fill(LinearGradient(gradient: Gradient(colors: self.gradientB), startPoint: .topLeading, endPoint: .bottomLeading)).edgesIgnoringSafeArea(.all)
.opacity(self.firstPlane ? 0 : 1)

TabView(selection: $selected){
Text("☀️").font(.title).tag(0)
Text("🌦").font(.title).tag(1)
Text("").font(.title).tag(2)
}.indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))
.tabViewStyle(PageTabViewStyle())
}.onChange(of: selected) { newselected in
print("\(newselected)!")
withAnimation (.easeInOut(duration: 0.7)){
self.setGradient(gradient: [Color.random(), Color.random()])
}
}
}
}

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

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit b81947f

Please sign in to comment.