[Swift]UIKit学习之滑块控件UISwitch的用法

UIKit学习之开关控件UISwitch的用法


UISwitch是一个开关控件。


UISwitch控件的创建:

(1) 在Stroyboard中使用Ctrl+Drag拖拽法创建

(2) 代码创建UISwitch:

let mySwitch = UISwitch()
//设置位置(开关大小无法设置)
mySwitch.center = CGPointMake(100,50);
//设置默认值(开true/关false)
mySwitch.on = true;

self.view.addSubview(mySwitch);


代码实例:

//  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.
    }
}


开发环境:

Xcode Version 7.0 (7A220)


参考资料:

http://www.hangge.com/blog/cache/detail_532.html

http://www.chuanke.com/1266915-124765.html



转载于:https://my.oschina.net/wangyongtao/blog/517814

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值