1. 程式人生 > >iOS學習五之UISwitch

iOS學習五之UISwitch

wid gray nal ins ride col white override after

iOS中的開關控件

只要添加下面的代碼即可實現

override func viewDidLoad() {

super.viewDidLoad()

// Do any additional setup after loading the view, typically from a nib.

//設置switch的位置和大小,但是switch本身的大小並不會隨width和height的設置而變化

let swi = UISwitch(frame: CGRect(x:100, y:100, width:100, height:40))

//控件開啟狀態的填充色

swi.onTintColor = UIColor.yellow

//控件關閉狀態的邊界色

swi.tintColor = UIColor.darkGray

//開關按鈕的顏色

swi.thumbTintColor = UIColor.orange

//添加交互方法

swi.addTarget(self, action: #selector(changeColor), for: .touchUpInside)

self.view.addSubview(swi)

}

//交互方法

@objc func changeColor(swi:UISwitch) {

//switch on的處理

if (swi.isOn) {

self.view.backgroundColor = UIColor.blue

//switch off的處理

} else {

self.view.backgroundColor = UIColor.white

}

}

iOS學習五之UISwitch