Customizing the Slider’s Appearance & Custom Slider in Swift
UISlider :
Simple default slider looks like below image. UISlider used to select a single value from a continuous range of value. Using slider select one value.
Open attributes inspector and set slider value and slider minimum & maximum value.
Now select UISlider and put in the storyboard. UISlider connects with ViewController file using @IBOutle. And create UISlider @IBAction in ViewController file. Use one label for display UISlider selected value. We can change UISlider minimumTrackColor, maximumTrackTintColor and thumbTintColor.
@IBOutlet weak var lblSliderValue: UILabel!
@IBOutlet weak var slider: UISlider!
override func viewDidLoad()
{
super.viewDidLoad()
lblSliderValue.text = "\(Int(slider.value))"
slider.minimumTrackTintColor = .green
slider.maximumTrackTintColor = .red
slider.thumbTintColor = .black
}
@IBAction func SliderTap(_ sender: UISlider)
{
let value = sender.value
lblSliderValue.text = "\(Int(value))"
}
Custom UISlider :
We can also make custom slider using default slider. First of all, create UISlider class which name is CustomSlider. And write below code in UISlider class.
@IBInspectable open var trackWidth:CGFloat = 2 {
didSet {setNeedsDisplay()}
}
override open func trackRect(forBounds bounds: CGRect) -> CGRect {
let defaultBounds = super.trackRect(forBounds: bounds)
return CGRect(
x: defaultBounds.origin.x,
y: defaultBounds.origin.y + defaultBounds.size.height/2 - trackWidth/2,
width: defaultBounds.size.width,
height: trackWidth
) }
Now select UISlider and CustomSlider class set as UISlider class.
Open attributes inspector look like below image. Set custom slider track width, slider value, minimum value and the maximum value of the slider.
UISlider connects with ViewController file using @IBOutle. And Create UISlider @IBAction in ViewController file. Use one label for display UISlider selected value.
Now set slider minimum track image and maximum track image and thumb image using viewDidLayoutSubviews().
@IBOutlet weak var lblCustomSliderValue: UILabel!
@IBOutlet weak var customSlider: CustomSlider!
override func viewDidLoad()
{
super.viewDidLoad()
lblCustomSliderValue.text = "\(Int(customSlider.value))"
}
override func viewDidLayoutSubviews()
{
self.customSlider.setMinimumTrackImage(UIImage(named: "slider-active"), for: .normal)
self.customSlider.setMaximumTrackImage(UIImage(named: "slider"), for: .normal)
self.customSlider.setThumbImage(UIImage(named: "knob"), for: .normal)
}
@IBAction func customSliderTap(_ sender: UISlider)
{
let value = sender.value
lblCustomSliderValue.text = "\(Int(value))"
}
You can easily download demo code by clicking here.
Contact us; If you have any query regarding iOS Application / Apple Watch Application / iMessage Extension / Today’s Extension OR you have your own application idea let us know. We have expert iOS team for your help.