class ViewController: UIViewController {
let mainWidth = UIScreen.main.bounds.width
let mainHeight = UIScreen.main.bounds.height
override func viewDidLoad() {
super.viewDidLoad()
//创建slider
self.createSlider()
self.createSwitch()
}
func createSlider() {
// 定义
let slider = UISlider(frame:CGRect(x: 20, y: 50, width: mainWidth-40, height: 40))
//slider.value = 1
// 设置最小值
slider.minimumValue = 0
// 设置最大值
slider.maximumValue = 1
// 设置按钮最小端图片
slider.minimumValueImage = UIImage.init(named: "2.png")
// 设置按钮最大端图片
slider.maximumValueImage = UIImage.init(named: "1.png")
// 设置圆点图片
slider.setThumbImage(UIImage.init(named: "yuan.png"), for: UIControlState.normal)
// 设置圆点颜色
slider.thumbTintColor = UIColor.red
// 设置滑动过的颜色
slider.minimumTrackTintColor = UIColor.green
// 设置未滑动过的颜色
slider.maximumTrackTintColor = UIColor.blue
// 添加事件
slider.addTarget(self, action: #selector(changeValue(slider:)), for: UIControlEvents.valueChanged)
self.view.addSubview(slider)
}
func changeValue(slider:UISlider){
print(slider.value)
}
func createSwitch(){
let switchview = UISwitch(frame: CGRect(x: 20, y: 100, width: mainWidth-40, height: 40))
self.view.addSubview(switchview)
switchview.addTarget(self, action: #selector(switchviewAction(sender:)), for: UIControlEvents.valueChanged)
//设置关闭状态下边框的颜色
switchview.tintColor = UIColor.blue
//开启的颜色
switchview.onTintColor = UIColor.red
//圆球的颜色
switchview.thumbTintColor = UIColor.gray
}
func switchviewAction(sender:UISwitch) {
sender.isOn = !sender.isOn
self.view.backgroundColor = sender.isOn ? UIColor.yellow : UIColor.red
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
网友评论