Пример range slider (выбор диапазона) + видео

xcode
swift

#1

Оно конечно не совсем сниппет, но думаю многим полезно будет)

Скачать


#2

Вот измененная версия части кода под Swift 3

 private func loadNib() {
    let view = UINib(nibName: "RangeSlider", bundle: Bundle.init(for: type(of: self))).instantiate(withOwner: self, options: nil).first as! UIView
    view.frame = bounds
    view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    addSubview(view)
 }

  override func layoutSubviews() {
    super.layoutSubviews()
    
    let minX = xForValue(value: selectedMin)
    let maxX = frame.width - xForValue(value: selectedMax)
    
    minThumbLayout.constant = minX - minThumb.frame.width / 2
    maxThumbLayout.constant = maxX - maxThumb.frame.width / 2
    
    minTrackLayout.constant = minX
    maxTrackLayout.constant = maxX
}

private func xForValue(value: CGFloat) -> CGFloat {
    return (((frame.width - padding * 2) * (value - minimum)) / (maximum - minimum)) + padding
}

private func valueForX(x: CGFloat) -> CGFloat {
    return minimum + (x - padding) / (frame.width - padding * 2) * (maximum - minimum)
}

override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
    let touchPoint = touch.location(in: self)
    if minThumb.frame.contains(touchPoint) {
        minThumbOn = true;
        distanceFromCenter = touchPoint.x - minThumb.center.x
    } else if maxThumb.frame.contains(touchPoint) {
        maxThumbOn = true;
        distanceFromCenter = touchPoint.x - maxThumb.center.x
    }
    return true
}

override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
    
    if !minThumbOn && !maxThumbOn {
        return true
    }
    
    let touchPoint = touch.location(in: self)
    
    if minThumbOn {
        selectedMin = valueForX(x: max(xForValue(value: minimum), min(touchPoint.x - distanceFromCenter, xForValue(value: selectedMax - minRange))))
    }
    
    if maxThumbOn {
        selectedMax = valueForX(x: min(xForValue(value: maximum), max(touchPoint.x - distanceFromCenter, xForValue(value: selectedMin + minRange))))
    }
    
    setNeedsLayout()
    sendActions(for: .valueChanged)
    
    return true
}

override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
    minThumbOn = false
    maxThumbOn = false
}