Skip to content

Instantly share code, notes, and snippets.

@theoknock
Last active March 26, 2024 14:59
Show Gist options
  • Save theoknock/3e7115af0f40c85bad6c46265319dd21 to your computer and use it in GitHub Desktop.
Save theoknock/3e7115af0f40c85bad6c46265319dd21 to your computer and use it in GitHub Desktop.
Adds a UISlider to a SwiftUI view. The track is replaced by a linear gradient, which has the same height as the thumb.
import SwiftUI
import UIKit
struct CustomUISlider: UIViewRepresentable {
@Binding var value: Double
var range: ClosedRange<Double>
func makeUIView(context: Context) -> UISlider {
let slider = UISlider(frame: .zero)
slider.minimumTrackTintColor = UIColor.clear
slider.maximumTrackTintColor = UIColor.clear
slider.minimumValue = Float(range.lowerBound)
slider.maximumValue = Float(range.upperBound)
slider.value = Float(value)
slider.addTarget(
context.coordinator,
action: #selector(Coordinator.valueChanged(_:)),
for: .valueChanged
)
return slider
}
func updateUIView(_ uiView: UISlider, context: Context) {
uiView.value = Float(value)
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject {
var parent: CustomUISlider
init(_ parent: CustomUISlider) {
self.parent = parent
}
@objc func valueChanged(_ sender: UISlider) {
parent.value = Double(sender.value)
}
}
}
struct CustomSliderView: View {
@State private var yellowCyanSliderValue: Double = 0.625
@State private var magentaGreenSliderValue: Double = 0.25
var body: some View {
Spacer()
ZStack {
RoundedRectangle(cornerRadius: 15)
.fill(LinearGradient(gradient: Gradient(colors: [Color.init(uiColor: .yellow), Color.init(uiColor: .cyan)]), startPoint: .leading, endPoint: .trailing))
.frame(height: 30)
CustomUISlider(value: $yellowCyanSliderValue, range: 0...1)
}
.frame(height: 30)
.padding(.horizontal)
Spacer()
ZStack {
RoundedRectangle(cornerRadius: 15)
.fill(LinearGradient(gradient: Gradient(colors: [Color.init(uiColor: .magenta), Color.init(uiColor: .green)]), startPoint: .leading, endPoint: .trailing))
.frame(height: 30)
CustomUISlider(value: $magentaGreenSliderValue, range: 0...1)
}
.frame(height: 30)
.padding(.horizontal)
Spacer()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment