Skip to content

Instantly share code, notes, and snippets.

@aibobrov
Created September 17, 2018 14:06
Show Gist options
  • Save aibobrov/0b26fde08a1fa385204019bfa4ade745 to your computer and use it in GitHub Desktop.
Save aibobrov/0b26fde08a1fa385204019bfa4ade745 to your computer and use it in GitHub Desktop.
Simple SteppedSlider in swift. Subclass of UISlider
import UIKit
@IBDesignable
class SteppedSlider: UISlider {
@IBInspectable var stepSize: Int = 1
@IBInspectable var normalThumbImage: UIImage? {
get {
return thumbImage(for: .normal)
}
set {
setThumbImage(newValue, for: .normal)
}
}
@IBInspectable var trackHeight: CGFloat = 12
var valueChanged: ((Int) -> Void)?
var ticksCount: Int {
return Int((maximumValue - minimumValue) / Float(stepSize))
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
minimumValue = 0
addTarget(self, action: #selector(sliderValueChanged(_:)), for: .valueChanged)
}
override func trackRect(forBounds bounds: CGRect) -> CGRect {
var rect = super.trackRect(forBounds: bounds)
rect.size.height = trackHeight
return rect
}
@objc func sliderValueChanged(_ sender: SteppedSlider) {
let value = Int(sender.value / Float(sender.stepSize))
sender.setValue(Float(value), animated: !isContinuous)
valueChanged?(value)
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setThumbImage(normalThumbImage, for: .normal)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment