UISwitch
NSObject ->UIResponder -> UIView ->UIControl -> UISwitch
概述
使用UISwitch
类创建和管理使用开/关的按钮,例如:设置 ->飞行模式/蓝牙的开关按钮。
当用户滑动开关按钮的时候,UISwitch
会发送UIControlEventValueChanged
消息,通过侦听这个消息,做出相应的处理。
样式图:
颜色属性对应图:
示例
先看自定义效果图
默认效果如下:
主要用法通过下面代码说明:
class ViewController: UIViewController {
var btnSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
//初始化btnSwitch,width, height属性会被忽略
btnSwitch = UISwitch(frame: CGRect(x: 0 , y: 0, width: 200, height: 100))
btnSwitch.center = CGPoint(x: self.view.bounds.width / 2, y: 200)
self.view.addSubview(btnSwitch)
//添加事件处理
btnSwitch.addTarget(self, action: "switchHandler:", forControlEvents: UIControlEvents.ValueChanged)
//on状态下背景颜色
btnSwitch.onTintColor = UIColor.brownColor()
//off 状态下背景的边框颜色
btnSwitch.tintColor = UIColor.redColor()
//滑块颜色
btnSwitch.thumbTintColor = UIColor.blueColor()
//设置无效
btnSwitch.onImage = UIImage(named: "icon")
//设置无效
btnSwitch.offImage = UIImage(named: "icon")
//动画方式设置 on/off 状态
btnSwitch.setOn(true, animated: true)
print("width: \(btnSwitch.frame.width), height: \(btnSwitch.frame.height)")
// width: 51.0, height: 31.0
}
// 处理函数
func switchHandler(e: UIControlEvents) {
//查看是否处于on状态
print("status:\(btnSwitch.on)")
}
}