-
Notifications
You must be signed in to change notification settings - Fork 9
/
Knob.swift
91 lines (73 loc) · 2.24 KB
/
Knob.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//
// KnobView.swift
// AudioKit Synth One
//
// Created by Matthew Fecher on 7/20/17.
// Copyright © 2017 AudioKit Pro. All rights reserved.
//
import UIKit
@IBDesignable
public class Knob: UIView {
var callback: (Double)->Void = { _ in }
@IBInspectable var minimum: Double = 0.0 {
didSet {
setNeedsDisplay()
}
}
@IBInspectable var maximum: Double = 1.0 {
didSet {
setNeedsDisplay()
}
}
@IBInspectable var value: Double = 0.5 {
didSet {
if value > maximum {
value = maximum
}
if value < minimum {
value = minimum
}
setNeedsDisplay()
}
}
// Knob properties
var knobValue: CGFloat {
return CGFloat((value - minimum) / (maximum - minimum))
}
var knobFill: CGFloat = 0
var knobSensitivity = 0.005
var lastX: CGFloat = 0
var lastY: CGFloat = 0
// Init / Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
contentMode = .redraw
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
self.isUserInteractionEnabled = true
contentMode = .redraw
}
override public func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
contentMode = .scaleAspectFit
clipsToBounds = true
}
public class override var requiresConstraintBasedLayout: Bool {
return true
}
public override func draw(_ rect: CGRect) {
KnobStyleKit.drawFMKnob(frame: CGRect(x:0,y:0, width: self.bounds.width, height: self.bounds.height), knobValue: knobValue)
}
// Helper
func setPercentagesWithTouchPoint(_ touchPoint: CGPoint) {
// Knobs assume up or right is increasing, and down or left is decreasing
let horizontalChange = Double(touchPoint.x - lastX) * knobSensitivity
value += horizontalChange * (maximum - minimum)
let verticalChange = Double(touchPoint.y - lastY) * knobSensitivity
value -= verticalChange * (maximum - minimum)
callback(value)
lastX = touchPoint.x
lastY = touchPoint.y
}
}