Repository navigation
Expand file tree
/
Copy pathHUDViewController.swift
More file actions
78 lines (67 loc) · 2.33 KB
/
Copy pathHUDViewController.swift
File metadata and controls
78 lines (67 loc) · 2.33 KB
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
//
// HUDViewController.swift
// SolAR
//
// Created by Roderic Campbell on 2/14/19.
// Copyright © 2019 Roderic Campbell. All rights reserved.
//
import UIKit
extension UIView {
class func initFromNib<T: UIView>() -> T {
return Bundle.main.loadNibNamed(String(describing: self), owner: nil, options: nil)?[0] as! T
}
}
class HUDViewController: UIViewController {
init() {
super.init(nibName: nil, bundle: nil)
}
let HUD = HUDView.instantiate()
let dataSource = PlanetDataSource()
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = HUD
view.translatesAutoresizingMaskIntoConstraints = false
}
func update(with distances: [Planet: Float]) {
if let focusPath = HUD.collectionView.indexPathsForVisibleItems.first {
let focusPlanet = dataSource.planets[focusPath.row]
let metersAway = distances[focusPlanet] ?? 0
HUD.distance.text = "\(metersAway.format(f: ".1")) real meters away"
}
}
override func viewDidLoad() {
let reuse = PlanetCell.reuseIdentifier
let nib = UINib(nibName: reuse,
bundle: nil)
HUD.collectionView.register(nib,
forCellWithReuseIdentifier: reuse)
HUD.collectionView.dataSource = dataSource
HUD.collectionView.delegate = self
// set a default value
let viewModel = Planet.sun.hudViewModel()
HUD.updateWith(viewModel: viewModel)
}
override func viewDidLayoutSubviews() {
if let layout = HUD.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.itemSize = HUD.collectionView.frame.size
}
}
}
extension HUDViewController: UICollectionViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset
guard let indexPath = self.HUD.collectionView.indexPathForItem(at: offset) else {
return
}
let planet = dataSource.planets[indexPath.row]
HUD.updateWith(viewModel: planet.hudViewModel())
}
}
extension Float {
func format(f: String) -> String {
return String(format: "%\(f)f", self)
}
}