is it possible to change the thumb of a Slider in SwiftUI like you can with a UISlider in UIKit? With a UISlider all you have to do is:
self.setThumbImage(UIImage(named: "Play_black"), for: .normal)
You can do this with SwiftUI-Introspect.
You are basically just accessing the underlying UISlider
from SwiftUI's Slider
, and then setting it there. This is much easier than creating a custom slider or making a representable.
Code:
struct ContentView: View {
@State private var value: Double = 0
var body: some View {
Slider(value: $value)
.introspectSlider { slider in
slider.setThumbImage(UIImage(named: "Play_black"), for: .normal)
}
}
}
Result (temporary image):
You can do this using UIKit's appearance
in SwiftUI.
Example:
struct CustomSlider : View {
@State private var value : Double = 0
init() {
let thumbImage = UIImage(systemName: "circle.fill")
UISlider.appearance().setThumbImage(thumbImage, for: .normal)
}
var body: some View {
Slider(value: $value)
}
}
onAppear
solution works, but not this one. –
Platform Ran into the same thing in iOS 16. The simplest way to customize it is with the .onAppear modifier:
Slider(value: $value)
.onAppear {
let thumbImage = UIImage(systemName: "circle.fill")
UISlider.appearance().setThumbImage(thumbImage, for: .normal)
}
Inspired by: https://developer.apple.com/forums/thread/719658
Update based on soundflix's comment
WARNING: this changes all sliders in the same view!!!
To be more clear, if you have a SampleView that contains this .onAppear code, the SampleView will pollute any view that contains SampleView (and any upstream and downstream views as well!), so be very careful with this solution if you want multiple slider styles in your app!
If you still want to use this code after understanding its limitations, you might want to move the .onAppear to the outer-most view to reflect what it does more accurately, like so:
var body: some View {
VStack {
Text("\(value1)")
Slider(value: $value1)
Text("\(value2)")
Slider(value: $value2)
}
.onAppear {
let thumbImage = UIImage(systemName: "circle.fill")
UISlider.appearance().setThumbImage(thumbImage, for: .normal)
}
}
Slider
views in your app. –
Platform onAppear
I declare in child/parent/grandparent views. –
Platform soundflix
; I have now modified my answer with more clarity. This .onAppear
will pollute an entire view hierarchy for sure (as you said child/parent/grandparent, etc.); however, if you have a view hierarchy that is not polluted by this .onAppear
already, you can start a different pollution within it by creating a different slider style. I do hope to find a native solution to not having this polluting behaviour, though... –
Penneypenni © 2022 - 2024 — McMap. All rights reserved.