您的位置:首页 > 产品设计 > UI/UE

12.UISwitch

2016-02-27 12:35 323 查看

UISwitch

UISwitch就是一个开关, 用起来也非常简单, 下面我们学习如何使用它

1. UISwitch创建

let switchView = UISwitch(frame: CGRect(x: 200, y: 20, width: 300, height: 300))
switchView.on = false
self.view.addSubview(switchView)


运行程序:



我们发现,开关的on属性可以控制UISwitch的开关状态,UISwitch的宽高是固定的,如我们设置宽高为300,300, 但它的实际大小是固定的.

2. UISwitch的定制

我们查看UISwitch的定义

@available(iOS 5.0, *)
public var onTintColor: UIColor? // 开状态的颜色
@available(iOS 6.0, *)
public var tintColor: UIColor! // 关状态的颜色
@available(iOS 6.0, *)
public var thumbTintColor: UIColor? // 中间小块的颜色

@available(iOS 6.0, *)
public var onImage: UIImage? // 开状态的图片,这属性没用了
@available(iOS 6.0, *)
public var offImage: UIImage? // 关状态的图片,这属性没用了


现在我们完成一个定制需求:

开关的开状态颜色是红色,关状态是黑色,中间小块的颜色是粉色

switchView.onTintColor = UIColor.redColor()
switchView.tintColor = UIColor.blackColor()
switchView.thumbTintColor = UIColor.magentaColor()


运行程序



现在我们使用图片试试:

switchView.onImage = UIImage(named: "onImage")
switchView.offImage = UIImage(named: "offImage")


运行程序:



我们发现,根本没卵用, 然后查看文档, 说ios7之后这两属性已经没效果了.+_+!!

3. UISwitch状态改变监听

和UISlider非常类似, 监听UIControlEvents.ValueChanged即可

switchView.addTarget(self, action: "switchChangeAction:", forControlEvents: .ValueChanged)

func switchChangeAction(sender: UISwitch) {
if(sender.on) {
print("开关已开")
} else {
print("开关已关")
}
}


运行程序, 我们切换开关的状态, 控制台会打印出不同的值

4. 完整代码


import UIKit

class ViewController6: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
let switchView = UISwitch(frame: CGRect(x: 200, y: 20, width: 300, height: 300))
switchView.on = true

self.view.addSubview(switchView)

switchView.onTintColor = UIColor.redColor() switchView.tintColor = UIColor.blackColor() switchView.thumbTintColor = UIColor.magentaColor()

// switchView.onImage = UIImage(named: "onImage")
// switchView.offImage = UIImage(named: "offImage")

switchView.addTarget(self, action: "switchChangeAction:", forControlEvents: .ValueChanged)
}

func switchChangeAction(sender: UISwitch) {
if(sender.on) {
print("开关已开")
} else {
print("开关已关")
}
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  UISwitch iOS开发 swift