-
Notifications
You must be signed in to change notification settings - Fork 16
/
TvOSSlider.swift
504 lines (416 loc) · 18.9 KB
/
TvOSSlider.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//
// TvOSSlider.swift
// TvOSSlider
//
// Created by David Cordero on 23.07.18.
// Copyright © 2018 David Cordero. All rights reserved.
//
import UIKit
import GameController
private let trackViewHeight: CGFloat = 5
private let thumbSize: CGFloat = 30
private let animationDuration: TimeInterval = 0.3
private let defaultValue: Float = 0
private let defaultMinimumValue: Float = 0
private let defaultMaximumValue: Float = 1
private let defaultIsContinuous: Bool = true
private let defaultThumbTintColor: UIColor = .white
private let defaultTrackColor: UIColor = .gray
private let defaultMininumTrackTintColor: UIColor = .blue
private let defaultFocusScaleFactor: CGFloat = 1.05
private let defaultStepValue: Float = 0.1
private let decelerationRate: Float = 0.92
private let decelerationMaxVelocity: Float = 1000
private let fineTunningVelocityThreshold: Float = 600
/// A control used to select a single value from a continuous range of values.
public final class TvOSSlider: UIControl {
// MARK: - Public
/// The slider’s current value.
@IBInspectable
public var value: Float {
get {
return storedValue
}
set {
storedValue = min(maximumValue, newValue)
storedValue = max(minimumValue, storedValue)
var offset = trackView.bounds.width * CGFloat((storedValue - minimumValue) / (maximumValue - minimumValue))
offset = min(trackView.bounds.width, offset)
thumbViewCenterXConstraint.constant = offset
}
}
/// The minimum value of the slider.
@IBInspectable
public var minimumValue: Float = defaultMinimumValue {
didSet {
value = max(value, minimumValue)
}
}
/// The maximum value of the slider.
@IBInspectable
public var maximumValue: Float = defaultMaximumValue {
didSet {
value = min(value, maximumValue)
}
}
/// A Boolean value indicating whether changes in the slider’s value generate continuous update events.
@IBInspectable
public var isContinuous: Bool = defaultIsContinuous
/// The color used to tint the default minimum track images.
@IBInspectable
public var minimumTrackTintColor: UIColor? = defaultMininumTrackTintColor {
didSet {
minimumTrackView.backgroundColor = minimumTrackTintColor
}
}
/// The color used to tint the default maximum track images.
@IBInspectable
public var maximumTrackTintColor: UIColor? {
didSet {
maximumTrackView.backgroundColor = maximumTrackTintColor
}
}
/// The color used to tint the default thumb images.
@IBInspectable
public var thumbTintColor: UIColor = defaultThumbTintColor {
didSet {
thumbView.backgroundColor = thumbTintColor
}
}
/// Scale factor applied to the slider when receiving the focus
@IBInspectable
public var focusScaleFactor: CGFloat = defaultFocusScaleFactor {
didSet {
updateStateDependantViews()
}
}
/// Value added or subtracted from the current value on steps left or right updates
public var stepValue: Float = defaultStepValue
/**
Sets the slider’s current value, allowing you to animate the change visually.
- Parameters:
- value: The new value to assign to the value property
- animated: Specify true to animate the change in value; otherwise, specify false to update the slider’s appearance immediately. Animations are performed asynchronously and do not block the calling thread.
*/
public func setValue(_ value: Float, animated: Bool) {
self.value = value
stopDeceleratingTimer()
if animated {
UIView.animate(withDuration: animationDuration) {
self.setNeedsLayout()
self.layoutIfNeeded()
}
}
}
/**
Assigns a minimum track image to the specified control states.
- Parameters:
- image: The minimum track image to associate with the specified states.
- state: The control state with which to associate the image.
*/
public func setMinimumTrackImage(_ image: UIImage?, for state: UIControl.State) {
minimumTrackViewImages[state.rawValue] = image
updateStateDependantViews()
}
/**
Assigns a maximum track image to the specified control states.
- Parameters:
- image: The maximum track image to associate with the specified states.
- state: The control state with which to associate the image.
*/
public func setMaximumTrackImage(_ image: UIImage?, for state: UIControl.State) {
maximumTrackViewImages[state.rawValue] = image
updateStateDependantViews()
}
/**
Assigns a thumb image to the specified control states.
- Parameters:
- image: The thumb image to associate with the specified states.
- state: The control state with which to associate the image.
*/
public func setThumbImage(_ image: UIImage?, for state: UIControl.State) {
thumbViewImages[state.rawValue] = image
updateStateDependantViews()
}
/// The minimum track image currently being used to render the slider.
public var currentMinimumTrackImage: UIImage? {
return minimumTrackView.image
}
/// Contains the maximum track image currently being used to render the slider.
public var currentMaximumTrackImage: UIImage? {
return maximumTrackView.image
}
/// The thumb image currently being used to render the slider.
public var currentThumbImage: UIImage? {
return thumbView.image
}
/**
Returns the minimum track image associated with the specified control state.
- Parameters:
- state: The control state whose minimum track image you want to use. Specify a single control state value for this parameter.
- Returns: The minimum track image associated with the specified state, or nil if no image has been set. This method might also return nil if you specify multiple control states in the state parameter. For a description of track images, see Customizing the Slider’s Appearance.
*/
public func minimumTrackImage(for state: UIControl.State) -> UIImage? {
return minimumTrackViewImages[state.rawValue]
}
/**
Returns the maximum track image associated with the specified control state.
- Parameters:
- state: The control state whose maximum track image you want to use. Specify a single control state value for this parameter.
- Returns: The maximum track image associated with the specified state, or nil if an appropriate image could not be retrieved. This method might return nil if you specify multiple control states in the state parameter. For a description of track images, see Customizing the Slider’s Appearance.
*/
public func maximumTrackImage(for state: UIControl.State) -> UIImage? {
return maximumTrackViewImages[state.rawValue]
}
/**
Returns the thumb image associated with the specified control state.
- Parameters:
- state: The control state whose thumb image you want to use. Specify a single control state value for this parameter.
- Returns: The thumb image associated with the specified state, or nil if an appropriate image could not be retrieved. This method might return nil if you specify multiple control states in the state parameter. For a description of track and thumb images, see Customizing the Slider’s Appearance.
*/
public func thumbImage(for state: UIControl.State) -> UIImage? {
return thumbViewImages[state.rawValue]
}
// MARK: - Initializers
/// :nodoc:
public override init(frame: CGRect) {
super.init(frame: frame)
setUpView()
}
/// :nodoc:
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUpView()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - UIControlStates
/// :nodoc:
public override var isEnabled: Bool {
didSet {
panGestureRecognizer.isEnabled = isEnabled
updateStateDependantViews()
}
}
/// :nodoc:
public override var isSelected: Bool {
didSet {
updateStateDependantViews()
}
}
/// :nodoc:
public override var isHighlighted: Bool {
didSet {
updateStateDependantViews()
}
}
/// :nodoc:
public override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
coordinator.addCoordinatedAnimations({
self.updateStateDependantViews()
}, completion: nil)
}
// MARK: - Private
private typealias ControlState = UInt
public var storedValue: Float = defaultValue
private var thumbViewImages: [ControlState: UIImage] = [:]
private var thumbView: UIImageView!
private var trackViewImages: [ControlState: UIImage] = [:]
private var trackView: UIImageView!
private var minimumTrackViewImages: [ControlState: UIImage] = [:]
private var minimumTrackView: UIImageView!
private var maximumTrackViewImages: [ControlState: UIImage] = [:]
private var maximumTrackView: UIImageView!
private var panGestureRecognizer: UIPanGestureRecognizer!
private var leftTapGestureRecognizer: UITapGestureRecognizer!
private var rightTapGestureRecognizer: UITapGestureRecognizer!
private var thumbViewCenterXConstraint: NSLayoutConstraint!
private var dPadState: DPadState = .select
private weak var deceleratingTimer: Timer?
private var deceleratingVelocity: Float = 0
private var thumbViewCenterXConstraintConstant: Float = 0
private func setUpView() {
setUpTrackView()
setUpMinimumTrackView()
setUpMaximumTrackView()
setUpThumbView()
setUpTrackViewConstraints()
setUpMinimumTrackViewConstraints()
setUpMaximumTrackViewConstraints()
setUpThumbViewConstraints()
setUpGestures()
NotificationCenter.default.addObserver(self, selector: #selector(controllerConnected(note:)), name: .GCControllerDidConnect, object: nil)
updateStateDependantViews()
}
private func setUpThumbView() {
thumbView = UIImageView()
thumbView.layer.cornerRadius = thumbSize/2
thumbView.backgroundColor = thumbTintColor
addSubview(thumbView)
}
private func setUpTrackView() {
trackView = UIImageView()
trackView.layer.cornerRadius = trackViewHeight/2
trackView.backgroundColor = defaultTrackColor
addSubview(trackView)
}
private func setUpMinimumTrackView() {
minimumTrackView = UIImageView()
minimumTrackView.layer.cornerRadius = trackViewHeight/2
minimumTrackView.backgroundColor = minimumTrackTintColor
addSubview(minimumTrackView)
}
private func setUpMaximumTrackView() {
maximumTrackView = UIImageView()
maximumTrackView.layer.cornerRadius = trackViewHeight/2
maximumTrackView.backgroundColor = maximumTrackTintColor
addSubview(maximumTrackView)
}
private func setUpTrackViewConstraints() {
trackView.translatesAutoresizingMaskIntoConstraints = false
trackView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
trackView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
trackView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
trackView.heightAnchor.constraint(equalToConstant: trackViewHeight).isActive = true
}
private func setUpMinimumTrackViewConstraints() {
minimumTrackView.translatesAutoresizingMaskIntoConstraints = false
minimumTrackView.leadingAnchor.constraint(equalTo: trackView.leadingAnchor).isActive = true
minimumTrackView.trailingAnchor.constraint(equalTo: thumbView.centerXAnchor).isActive = true
minimumTrackView.centerYAnchor.constraint(equalTo:trackView.centerYAnchor).isActive = true
minimumTrackView.heightAnchor.constraint(equalToConstant: trackViewHeight).isActive = true
}
private func setUpMaximumTrackViewConstraints() {
maximumTrackView.translatesAutoresizingMaskIntoConstraints = false
maximumTrackView.leadingAnchor.constraint(equalTo: thumbView.centerXAnchor).isActive = true
maximumTrackView.trailingAnchor.constraint(equalTo: trackView.trailingAnchor).isActive = true
maximumTrackView.centerYAnchor.constraint(equalTo:trackView.centerYAnchor).isActive = true
maximumTrackView.heightAnchor.constraint(equalToConstant: trackViewHeight).isActive = true
}
private func setUpThumbViewConstraints() {
thumbView.translatesAutoresizingMaskIntoConstraints = false
thumbView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
thumbView.widthAnchor.constraint(equalToConstant: thumbSize).isActive = true
thumbView.heightAnchor.constraint(equalToConstant: thumbSize).isActive = true
thumbViewCenterXConstraint = thumbView.centerXAnchor.constraint(equalTo: trackView.leadingAnchor, constant: CGFloat(value))
thumbViewCenterXConstraint.isActive = true
}
private func setUpGestures() {
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panGestureWasTriggered(panGestureRecognizer:)))
addGestureRecognizer(panGestureRecognizer)
leftTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(leftTapWasTriggered))
leftTapGestureRecognizer.allowedPressTypes = [NSNumber(value: UIPress.PressType.leftArrow.rawValue)]
leftTapGestureRecognizer.allowedTouchTypes = [NSNumber(value: UITouch.TouchType.indirect.rawValue)]
addGestureRecognizer(leftTapGestureRecognizer)
rightTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(rightTapWasTriggered))
rightTapGestureRecognizer.allowedPressTypes = [NSNumber(value: UIPress.PressType.rightArrow.rawValue)]
rightTapGestureRecognizer.allowedTouchTypes = [NSNumber(value: UITouch.TouchType.indirect.rawValue)]
addGestureRecognizer(rightTapGestureRecognizer)
}
private func updateStateDependantViews() {
minimumTrackView.image = minimumTrackViewImages[state.rawValue] ?? minimumTrackViewImages[UIControl.State.normal.rawValue]
maximumTrackView.image = maximumTrackViewImages[state.rawValue] ?? maximumTrackViewImages[UIControl.State.normal.rawValue]
thumbView.image = thumbViewImages[state.rawValue] ?? thumbViewImages[UIControl.State.normal.rawValue]
if isFocused {
transform = CGAffineTransform(scaleX: focusScaleFactor, y: focusScaleFactor)
}
else {
transform = CGAffineTransform.identity
}
}
@objc private func controllerConnected(note: NSNotification) {
guard let controller = note.object as? GCController else { return }
guard let micro = controller.microGamepad else { return }
let threshold: Float = 0.7
micro.reportsAbsoluteDpadValues = true
micro.dpad.valueChangedHandler = {
[weak self] (pad, x, y) in
if x < -threshold {
self?.dPadState = .left
}
else if x > threshold {
self?.dPadState = .right
}
else {
self?.dPadState = .select
}
}
}
@objc
private func handleDeceleratingTimer(timer: Timer) {
let centerX = thumbViewCenterXConstraintConstant + deceleratingVelocity * 0.01
let percent = centerX / Float(trackView.frame.width)
value = minimumValue + ((maximumValue - minimumValue) * percent)
if isContinuous {
sendActions(for: .valueChanged)
}
thumbViewCenterXConstraintConstant = Float(thumbViewCenterXConstraint.constant)
deceleratingVelocity *= decelerationRate
if !isFocused || abs(deceleratingVelocity) < 1 {
stopDeceleratingTimer()
}
}
private func stopDeceleratingTimer() {
deceleratingTimer?.invalidate()
deceleratingTimer = nil
deceleratingVelocity = 0
sendActions(for: .valueChanged)
}
// MARK: - Actions
@objc
private func panGestureWasTriggered(panGestureRecognizer: UIPanGestureRecognizer) {
let translation = Float(panGestureRecognizer.translation(in: self).x)
let velocity = Float(panGestureRecognizer.velocity(in: self).x)
switch panGestureRecognizer.state {
case .began:
stopDeceleratingTimer()
thumbViewCenterXConstraintConstant = Float(thumbViewCenterXConstraint.constant)
case .changed:
let centerX = thumbViewCenterXConstraintConstant + translation / 5
let percent = centerX / Float(trackView.frame.width)
value = minimumValue + ((maximumValue - minimumValue) * percent)
if isContinuous {
sendActions(for: .valueChanged)
}
case .ended, .cancelled:
thumbViewCenterXConstraintConstant = Float(thumbViewCenterXConstraint.constant)
if abs(velocity) > fineTunningVelocityThreshold {
let direction: Float = velocity > 0 ? 1 : -1
deceleratingVelocity = abs(velocity) > decelerationMaxVelocity ? decelerationMaxVelocity * direction : velocity
deceleratingTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(handleDeceleratingTimer(timer:)), userInfo: nil, repeats: true)
}
else {
stopDeceleratingTimer()
}
default:
break
}
}
@objc
private func leftTapWasTriggered() {
setValue(value-stepValue, animated: true)
}
@objc
private func rightTapWasTriggered() {
setValue(value+stepValue, animated: true)
}
public override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
for press in presses {
switch press.type {
case .select where dPadState == .left:
panGestureRecognizer.isEnabled = false
leftTapWasTriggered()
case .select where dPadState == .right:
panGestureRecognizer.isEnabled = false
rightTapWasTriggered()
case .select:
panGestureRecognizer.isEnabled = false
default:
break
}
}
panGestureRecognizer.isEnabled = true
super.pressesBegan(presses, with: event)
}
}