Skip to content

Instantly share code, notes, and snippets.

@todbot
Last active July 18, 2022 04:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save todbot/72ce22c917f9de9e9bd99b15252da5f3 to your computer and use it in GitHub Desktop.
Save todbot/72ce22c917f9de9e9bd99b15252da5f3 to your computer and use it in GitHub Desktop.
Playing around with SwiftUI Sliders, copying Carlyn
//
// slidertest - copy into a blank Playground
//
// Created by Tod Kurt on 7/17/22.
//
import SwiftUI
// given 0-1 val, return 0-1 with log curve
func logtaper(_ v: Double) -> Double {
return log10(1 + 9*v) // log10(1) = 0, log10(10) = 1
}
// given 0-1 val, return 0-1 with x^2 curve
func squaredtaper(_ v: Double) -> Double {
return (v*v)
}
// give 0-1 val, return 0-1 with sqrt(x) curve, (similar to logtaper)
func sqrttaper(_ v: Double) -> Double {
return sqrt(v)
}
// normalize val to 0-1, apply taper
// return value within vmin-max
func mapToTaper( val:Double, vmin:Double, vmax:Double,
taper: (Double)->Double ) -> Double {
let vrange = vmax - vmin
let normalized_val = (val-vmin) / vrange
return vmin + (vrange * taper(normalized_val))
}
struct ContentView: View {
@State var sliderVal1:Double = 15
@State var sliderVal2:Double = 15
@State var sliderVal3:Double = 15
var sliderVal1Display:Double {
get { mapToTaper(val:sliderVal1, vmin:10,vmax:20, taper:logtaper) }
}
var sliderVal2Display:Double {
get { mapToTaper(val:sliderVal2, vmin:10,vmax:20, taper:squaredtaper) }
}
var sliderVal3Display:Double {
get { mapToTaper(val:sliderVal3, vmin:10,vmax:20, taper:sqrttaper) }
}
var body: some View {
VStack {
Text(String(format: "sliderLog %2.1f", sliderVal1Display))
.padding()
Slider(value:$sliderVal1, in:10...20)
Text(String(format: "sliderSquared %2.1f", sliderVal2Display))
.padding()
Slider(value:$sliderVal2, in:10...20)
Text(String(format: "sliderSqrt %2.1f", sliderVal3Display))
.padding()
Slider(value:$sliderVal3, in:10...20)
}
}
}
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