-1

How do you create a custom height for a Slider when the slider has been created programmatically?

The answers to this similar question explain how to do it when the Slide is setup with a Storyboard. What if you aren't using a Storyboard and the slider is set up along these lines programmatically? Thanks!

let slider: UISlider = {
    let slider = UISlider()
    slider.minimumValue = 1
    slider.maximumValue = 7
    slider.value = 1
    slider.maximumTrackTintColor = UIColor.red
    slider.minimumTrackTintColor = UIColor.green
    slider.thumbTintColor = UIColor.blue
    slider.isContinuous = true
    slider.translatesAutoresizingMaskIntoConstraints = false
    return slider
}()
Ben
  • 3,346
  • 6
  • 32
  • 51

1 Answers1

2

You'll need to create a custom slider, and override trackRect(forBounds bounds: CGRect) -> CGRect

class CustomSlider: UISlider {
   let trackHeight: CGFloat = 12 //desired track width, in points
   override func trackRect(forBounds bounds: CGRect) -> CGRect {
      let track = super.trackRect(forBounds: bounds)
      return CGRect(x: track.origin.x, y: track.origin.y, width: track.width, height: trackHeight)
   }
}

and change your implementation to use this

let slider: CustomSlider = {
       let slider = CustomSlider()
       slider.minimumValue = 1
       slider.maximumValue = 7
       slider.value = 1
       slider.maximumTrackTintColor = UIColor.red
       slider.minimumTrackTintColor = UIColor.green
       slider.thumbTintColor = UIColor.blue
       slider.isContinuous = true
       slider.translatesAutoresizingMaskIntoConstraints = false
       return slider
   }()
flanker
  • 3,840
  • 1
  • 12
  • 20