Created
January 22, 2020 22:53
-
-
Save CodeSlicing/c42e367eaf396a6dd8eb8e61dd362fbe to your computer and use it in GitHub Desktop.
Animates a gradient behind a picker to indicate the severity of the choice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// GradientPickerDemo.swift | |
// DemoGists | |
// | |
// Permission is hereby granted, free of charge, to any person obtaining a copy | |
// of this software and associated documentation files (the "Software"), to deal | |
// in the Software without restriction, including without limitation the rights | |
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies | |
// of the Software, and to permit persons to whom the Software is furnished to do so, | |
// subject to the following conditions: | |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, | |
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | |
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR | |
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN | |
// AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION | |
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
// | |
// Created by Adam Fordyce on 22/01/2020. | |
// Copyright © 2020 Adam Fordyce. All rights reserved. | |
// | |
import SwiftUI | |
import PureSwiftUI | |
struct GradientPickerDemo: View { | |
@State private var tipPercentageIndex = 2 | |
let tipPercentages = [0, 10, 15, 20, 25] | |
var gradientOffset: CGFloat { | |
let numSteps = CGFloat(tipPercentages.count - 1) | |
return CGFloat(tipPercentageIndex * 2) / numSteps - 1 | |
} | |
var body: some View { | |
Form { | |
Section(header: Text("How much tip do you want to leave?")) { | |
Picker("Tip percentage", selection: $tipPercentageIndex) { | |
ForEach(0 ..< tipPercentages.count) { | |
Text("\(self.tipPercentages[$0])%") | |
} | |
} | |
.pickerStyle(SegmentedPickerStyle()) | |
.listRowBackground( | |
LinearGradient(gradient: Gradient(colors: [.green, .red]), | |
startPoint: .init(x: gradientOffset, y: 0), | |
endPoint: .init(x: gradientOffset + 1, y: 0)) | |
.animation(.spring())) | |
} | |
} | |
} | |
} | |
struct GradientPickerDemo_Previews: PreviewProvider { | |
struct GradientPickerDemo_Harness: View { | |
var body: some View { | |
GradientPickerDemo() | |
} | |
} | |
static var previews: some View { | |
GradientPickerDemo_Harness() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment