UISwitch

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)")
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值