★ スイッチの生成
let switch1 = UISwitch()
let switch2: UISwitch = UISwitch()
★ スイッチON/OFF設定
// スイッチON
switch1.on = true
// アニメーションを指定できる
switch1.setOn(true, animated: true)
// スイッチOFF
switch1.on = false
// アニメーションを指定できる
switch1.setOn(false, animated: false)
★ スイッチの中心位置を設定
switch1.center = CGPointMake(50, 50)
switch1.layer.position = CGPoint(x: 50, y: 50)
★ スイッチの位置を設定
// サイズは変更不可
switch1.frame = CGRectMake(100, 300, 0, 0)
★ ON時の背景色を設定
switch1.onTintColor = UIColor.yellowColor()
★ OFF時の周りのボーダーカラーを設定
switch1.tintColor = UIColor.blueColor()
★ スイッチのツマミのカラーを設定
switch1.thumbTintColor = UIColor.orangeColor()
// イメージを設定
switch1.thumbTintColor = UIColor(patternImage: UIImage(named: "image")!)
★ スイッチが切り替えられた時のメソッドを定義
switch1.addTarget(self, action: "changeSwitch:", forControlEvents: .ValueChanged)
func changeSwitch(sender: UISwitch) {
if sender.on {
print("ON!")
} else {
print("OFF!")
}
}
★ Viewにスイッチを追加する
self.view.addSubview(switch1)