Skip to content

Instantly share code, notes, and snippets.

@Coder-ACJHP
Created April 15, 2019 11:08
Show Gist options
  • Save Coder-ACJHP/a674602f9ed06d9f83c92b67461e282d to your computer and use it in GitHub Desktop.
Save Coder-ACJHP/a674602f9ed06d9f83c92b67461e282d to your computer and use it in GitHub Desktop.
//
// UICAwesomeSlider.swift
//
// Created by Coder ACJHP on 15.04.2019.
// Copyright © 2019 FitBest Bilgi Teknolojileri. All rights reserved.
//
import UIKit
class UICValueLabeledSlider: UISlider {
let currentValueLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
currentValueLabel.frame = .zero
currentValueLabel.backgroundColor = .red
currentValueLabel.textColor = .white
currentValueLabel.font = UIFont.boldSystemFont(ofSize: 13)
currentValueLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight]
currentValueLabel.alpha = 0
addSubview(currentValueLabel)
layer.cornerRadius = frame.height / 2
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func trackRect(forBounds bounds: CGRect) -> CGRect {
let customBounds = CGRect(origin: bounds.origin, size: CGSize(width: bounds.width, height: 15))
super.trackRect(forBounds: customBounds)
return customBounds
}
private func getThumbViewRect() -> CGRect {
return self.thumbRect(forBounds: self.bounds, trackRect: self.trackRect(forBounds: self.bounds), value: self.value)
}
private func updateValueLabelValueAndPosition() {
let thumbRect = getThumbViewRect()
currentValueLabel.frame = thumbRect
currentValueLabel.text = String(format: "%.2f", self.value)
currentValueLabel.center = CGPoint(x: thumbRect.midX, y: thumbRect.minY - self.currentValueLabel.frame.height)
}
private func animateValueLabel(fading: Bool = true) {
let thumbRect = getThumbViewRect()
UIView.animate(withDuration: 0.3) {
self.currentValueLabel.alpha = fading ? 1.0 : 0.0
self.currentValueLabel.center.y = fading ? thumbRect.minY - self.currentValueLabel.frame.height : thumbRect.minY
}
}
override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
let touchPoint = touch.location(in: self)
if getThumbViewRect().contains(touchPoint) {
animateValueLabel()
}
return super.beginTracking(touch, with: event)
}
override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
updateValueLabelValueAndPosition()
return super.continueTracking(touch, with: event)
}
override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
animateValueLabel(fading: false)
return super.endTracking(touch, with: event)
}
override func cancelTracking(with event: UIEvent?) {
return super.cancelTracking(with: event)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment