Home > AI > IOS > SwiftUI >

Slider which thumb is customized

Example:


import SwiftUI
import UIKit



struct SliderView: UIViewRepresentable {
    var thumbTintColor: UIColor = .blue
    @Binding var value: Float
    
    func makeUIView(context: Context) -> UISlider {
        let slider = UISlider(frame: .zero)
        slider.thumbTintColor = thumbTintColor
        slider.minimumValue = 0
        slider.maximumValue = 100
        slider.value = value
        let img: UIImage = self.thumbImage()
        slider.setThumbImage(img, for: .normal) // idle
        slider.setThumbImage(img, for: .highlighted) // moving
        slider.addTarget(context.coordinator, action: #selector(Coordinator.valueChanged(_:)), for: .valueChanged)
        return slider
    }
    
    func updateUIView(_ uiView: UISlider, context: Context) {
        uiView.value = self.value
    }
    
    func makeCoordinator() -> Coordinator {
        return Coordinator(value: $value)
    }
    
    
    
    class Coordinator: NSObject {
        var value: Binding<Float>
        
        init(value: Binding<Float>) {
            self.value = value
            super.init()
        }
        
        @objc func valueChanged(_ sender: UISlider) {
            self.value.wrappedValue = sender.value
        }
    }
    
    
    
    
    // customized thumb
    var thumbRadius: CGFloat
    var thumbForeColor: UIColor = .white
    var thumbBorderColor: UIColor = UIColor(Color.blue)
    var thumbBorderWidth: CGFloat = 2
    
    private func thumbImage() -> UIImage {
        let thumb = UIView()
        thumb.backgroundColor = thumbForeColor
        thumb.layer.borderWidth = thumbBorderWidth
        thumb.layer.borderColor = thumbBorderColor.cgColor
        
        thumb.frame = CGRect(x: 0, y: thumbRadius/2, width: thumbRadius, height: thumbRadius)
        thumb.layer.cornerRadius = thumbRadius / 2
        let renderer = UIGraphicsImageRenderer(bounds: thumb.bounds)
        return renderer.image { rendererContext in
            thumb.layer.render(in: rendererContext.cgContext)
        }
    }
}


Leave a Reply