Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // MyDoubleSlider.swift
- // Jour-7-CustomControls
- //
- // Created by Ludivine Maret on 22/11/2017.
- // Copyright © 2017 student. All rights reserved.
- //
- import UIKit
- class MyDoubleSlider: UIView {
- var valueMin : Float = 0
- var valueMax : Float = 1
- override init(frame: CGRect) {
- super.init(frame: frame)
- setupGestures()
- }
- required init?(coder aDecoder: NSCoder) {
- super.init(coder: aDecoder)
- setupGestures()
- }
- var panRecognizer = UIPanGestureRecognizer()
- func setupGestures() {
- panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panEvent(_:)))
- self.addGestureRecognizer(panRecognizer)
- }
- enum InteractionStatus {
- case none
- case panMin
- case panMax
- }
- var interactionStatus = InteractionStatus.none
- @objc func panEvent(_ recognizer : UIPanGestureRecognizer) {
- let r = CGFloat(8) // 8px
- let w = bounds.width
- let gmin = CGFloat(0)
- let gmax = w - 2 * r
- switch recognizer.state {
- case .began:
- let panX = recognizer.location(in: self).x
- let minX = CGFloat(valueMin) * (gmax - gmin) + gmin + r
- let maxX = CGFloat(valueMax) * (gmax - gmin) + gmin + r
- let distToMin = abs(minX - panX)
- let distToMax = abs(maxX - panX)
- if distToMin < distToMax {
- interactionStatus = .panMin
- } else {
- interactionStatus = .panMax
- }
- case .changed:
- let panX = recognizer.location(in: self).x
- //update value
- var value = (panX - gmin - r) / (gmax-gmin)
- value = min(1.0, max(0.0, value))
- if interactionStatus == .panMin {
- valueMin = Float(value)
- } else {
- valueMax = Float(value)
- }
- setNeedsDisplay() // Ne jamais appeler draw(rect:)
- case .ended:
- interactionStatus = .none
- case .possible, .cancelled, .failed:
- interactionStatus = .none
- // do nothing
- break;
- }
- print(recognizer)
- }
- // Only override draw() if you perform custom drawing.
- // An empty implementation adversely affects performance during animation.
- override func draw(_ rect: CGRect) {
- // Drawing code
- let r = CGFloat(8) // 8px
- let w = bounds.width
- let h = bounds.height
- let gmin = CGFloat(0)
- let gmax = w - 2 * r
- let pmin = CGFloat(valueMin) * (gmax - gmin) + gmin
- let pmax = CGFloat(valueMax) * (gmax - gmin) + gmin
- // Trait de fond
- UIColor.blue.set()
- UIRectFill(CGRect(x: r, y: h/2, width: w - 2 * r, height: 2))
- // Puce 1
- UIColor.red.set()
- UIRectFill(CGRect(x: pmin, y: h/2-r, width: 2 * r, height: 2 * r))
- // Puce 2
- UIColor.green.set()
- UIRectFill(CGRect(x: pmax, y: h/2-r, width: 2 * r, height: 2 * r))
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement