Changing Slider thumb in SwiftUI

Viewed 2624

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)

3 Answers

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)
    }
}
Related