UISwitch控件
UIControl 控制控件的基類 凡是繼承自這個類的子類都可以實現addTarget(_ target: Any?, action: Selector, for controlEvents: UIControlEvents)
UIControl的子類:UISwitch(開關控件),UISlider(滑塊控件),UISegmentedControl(分段控件),UIStepper(計步控件)
創建UISwitch
let aSwitch = UISwitch()
只需要給位置不需要給大小(系統默認)
aSwitch.frame.origin = CGPoint(x: 50, y: 50)
打開時的內部渲染顏色
aSwitch.onTintColor = UIColor.blue
邊框顏色
aSwitch.tintColor = UIColor.red
滑塊的顏色
aSwitch.thumbTintColor = UIColor.green
添加UISwich的關聯事件
aSwitch.addTarget(self, action: #selector(switchAction), for: .valueChanged)
將aSwitch添加到視圖中
self.view.addSubview(aSwitch)
創建一個新的方法來實現關聯事件(判斷開關的狀態)
func switchAction(sender:UISwitch){
if sender.isOn {
print("打開移動蜂窩")
}else{
print("關閉移動蜂窩")
}
}