
var myButton: UIButton?
var mySwitch: UISwitch?
override func viewDidLoad() {
self.myButton = UIButton.buttonWithType(.System) as? UIButton
self.myButton!.frame = CGRectMake(self.view.frame.width/2 - 100, 200, 200, 100)
self.myButton!.setTitle("change state", forState: UIControlState.Normal)
self.myButton!.addTarget(self, action: "buttonAction", forControlEvents: UIControlEvents.TouchUpInside)
self.mySwitch = UISwitch(frame:CGRectMake(self.view.frame.width/2 - 20, 400, 10, 100))
self.mySwitch!.on = true
self.mySwitch!.onTintColor = UIColor.lightGrayColor()
self.mySwitch!.tintColor = UIColor.greenColor()
self.mySwitch!.thumbTintColor = UIColor.blackColor()
self.mySwitch!.addTarget(self,action:Selector("switchChange:"), forControlEvents: UIControlEvents.ValueChanged)
// 扩展:还可以通过设置 onImage、offImage 来来添加图片
self.view.addSubview(self.myButton!)
self.view.addSubview(self.mySwitch!)
}
/// 按钮相应事件
func buttonAction() {
if self.mySwitch!.on{
println("Switch is on")
self.mySwitch!.setOn(false, animated:true)
}else{
println("Switch is off")
self.mySwitch!.setOn(true, animated:true)
}
}
/// 开关控制事件
func switchChange(switchState: UISwitch) {
if switchState.on {
println("Switch is on")
} else {
println("Switch is off")
}
}
文章最后更新时间:2015年3月18日10:58:09。参考资料如下:
UIKit User
Interface Catalog: Switches
原文地址:http://blog.csdn.net/jinnchang/article/details/44407193