回答編集履歴
1
追記
test
CHANGED
@@ -43,3 +43,113 @@
|
|
43
43
|
@objc func switchChanged(sender: UISwitch) {
|
44
44
|
|
45
45
|
```
|
46
|
+
|
47
|
+
|
48
|
+
|
49
|
+
---
|
50
|
+
|
51
|
+
|
52
|
+
|
53
|
+
とりあえず私の手元で動いてるのを貼ってみますので、お試しください。
|
54
|
+
|
55
|
+
(なお、import はまとめて最初に書くのが一般的なので、そうしてみました。)
|
56
|
+
|
57
|
+
|
58
|
+
|
59
|
+
```swift
|
60
|
+
|
61
|
+
import UIKit
|
62
|
+
|
63
|
+
import PlaygroundSupport
|
64
|
+
|
65
|
+
|
66
|
+
|
67
|
+
class UISwitchSample: UIView {
|
68
|
+
|
69
|
+
|
70
|
+
|
71
|
+
var label: UILabel!
|
72
|
+
|
73
|
+
|
74
|
+
|
75
|
+
override init(frame: CGRect) {
|
76
|
+
|
77
|
+
super.init(frame: frame)
|
78
|
+
|
79
|
+
|
80
|
+
|
81
|
+
// スイッチとラベルをのせるビュー
|
82
|
+
|
83
|
+
let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 150))
|
84
|
+
|
85
|
+
self.addSubview(view)
|
86
|
+
|
87
|
+
view.center = self.center
|
88
|
+
|
89
|
+
view.backgroundColor = UIColor.white
|
90
|
+
|
91
|
+
|
92
|
+
|
93
|
+
// ラベル
|
94
|
+
|
95
|
+
label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
|
96
|
+
|
97
|
+
label.center = CGPoint(x: view.frame.width/2, y: view.frame.height * 0.75)
|
98
|
+
|
99
|
+
label.textColor = UIColor.blue
|
100
|
+
|
101
|
+
label.textAlignment = NSTextAlignment.center
|
102
|
+
|
103
|
+
view.addSubview(label)
|
104
|
+
|
105
|
+
|
106
|
+
|
107
|
+
let sw = UISwitch(frame: CGRect(x: 0, y: 0, width: 60, height: 40))
|
108
|
+
|
109
|
+
view.addSubview(sw)
|
110
|
+
|
111
|
+
sw.center = CGPoint(x: view.frame.width/2, y: view.frame.height/2)
|
112
|
+
|
113
|
+
|
114
|
+
|
115
|
+
// スイッチをONにする
|
116
|
+
|
117
|
+
sw.setOn(true, animated: true)
|
118
|
+
|
119
|
+
label.text = "ON"
|
120
|
+
|
121
|
+
|
122
|
+
|
123
|
+
// 値が変わった時の処理を指定
|
124
|
+
|
125
|
+
sw.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
|
126
|
+
|
127
|
+
}
|
128
|
+
|
129
|
+
|
130
|
+
|
131
|
+
@objc func switchChanged(sender: UISwitch) {
|
132
|
+
|
133
|
+
// スイッチのon/off
|
134
|
+
|
135
|
+
if sender.isOn { label.text = "ON"}
|
136
|
+
|
137
|
+
else { label.text = "OFF" }
|
138
|
+
|
139
|
+
}
|
140
|
+
|
141
|
+
|
142
|
+
|
143
|
+
required init(coder aDecoder: NSCoder) {
|
144
|
+
|
145
|
+
fatalError("init(coder:) has not been implemented")
|
146
|
+
|
147
|
+
}
|
148
|
+
|
149
|
+
}
|
150
|
+
|
151
|
+
|
152
|
+
|
153
|
+
PlaygroundPage.current.liveView = UISwitchSample(frame: CGRect(x: 0, y: 0, width: 200, height: 150))
|
154
|
+
|
155
|
+
```
|