-
Notifications
You must be signed in to change notification settings - Fork 0
/
FullViewController.swift
101 lines (61 loc) · 2.63 KB
/
FullViewController.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
import UIKit
class FullViewController: UIViewController {
enum Position: String {
case Left, Center, Right
static let all: [Position] = [.Left, .Center, .Right]
}
@IBOutlet weak var positionLabel: UILabel!
@IBOutlet weak var animatedSwitch: UISwitch!
@IBOutlet weak var positionPicker: UIPickerView!
@IBOutlet weak var positionLabelLeadingConstraint: NSLayoutConstraint!
var position = Position.Left {
didSet {
self.configurePosition()
}
}
}
extension FullViewController: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return Position.all.count
}
}
extension FullViewController: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return Position.all[row].rawValue
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.position = Position.all[row]
}
}
extension FullViewController {
private func configurePosition() {
self.positionLabel.text = self.position.rawValue
let changes = {
var leadingConstraint: CGFloat = 0.0
switch self.position {
case .Left:
leadingConstraint = 8.0
case .Center:
leadingConstraint = (self.view.bounds.width - self.positionLabel.bounds.width) / 2.0
case .Right:
leadingConstraint = self.view.bounds.width - self.positionLabel.bounds.width - 8.0
}
self.positionLabelLeadingConstraint.constant = leadingConstraint
self.view.layoutIfNeeded()
}
let completion: (Bool) -> (Void) = { _ in
if let positionIndex = Position.all.index(of: self.position) {
self.positionPicker.selectRow(positionIndex, inComponent: 0, animated: false)
}
}
if self.animatedSwitch.isOn {
UIView.animate(withDuration: 0.5, animations: changes, completion: completion)
} else {
changes()
completion(false)
}
}
}