UIKit學習之開關控件UISwitch的用法html
UISwitch是一個開關控件。swift
UISwitch控件的建立:
ide
(1) 在Stroyboard中使用Ctrl+Drag拖拽法建立學習
(2) 代碼建立UISwitch:spa
let mySwitch = UISwitch() //設置位置(開關大小沒法設置) mySwitch.center = CGPointMake(100,50); //設置默認值(開true/關false) mySwitch.on = true; self.view.addSubview(mySwitch);
代碼實例:code
// ViewController.swift import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let mySwitch = UISwitch() //設置位置(開關大小沒法設置) mySwitch.center = CGPointMake(100,50); //設置默認值(開true/關false) mySwitch.on = true; mySwitch.addTarget(self, action: "switchDidChanged:", forControlEvents:UIControlEvents.ValueChanged) self.view.addSubview(mySwitch); } // func switchDidChanged(sender:UISwitch){ if(sender.on){ self.view.backgroundColor = UIColor.brownColor() myLabel.text = "開關已經打開"; myLabel.backgroundColor = UIColor.blueColor() } else { self.view.backgroundColor = UIColor.blackColor() myLabel.text = "開關已經關閉" myLabel.backgroundColor = UIColor.greenColor() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
開發環境:orm
Xcode Version 7.0 (7A220)htm
參考資料:blog
http://www.hangge.com/blog/cache/detail_532.htmlci
http://www.chuanke.com/1266915-124765.html