简单实现slider控件
import UIKit
class ViewController: UIViewController,sliderDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let slider = Slider(frame: CGRect(x: 100, y: 100, width: 200, height: 100))
//1.target
// slider.addTarget(self, action: #selector(didmove(_:)), forControlEvents: .ValueChanged)
//2.闭包
// slider.didchange = {
// sender in
// print(sender.value)
// }
//3.协议
slider.delegate = self
self.view.addSubview(slider)
}
func didmove(sender:Slider){
print(sender.value)
}
func sliderdelegate(slider: Slider) {
print(slider.value)
}
}
三种方法实现slider功能
import UIKit
//定义协议
protocol sliderDelegate {
func sliderdelegate(slider: Slider)
}
class Slider: UIControl{
//定义成员
var didchange : ((Slider)->Void)!
var minvalue : CGFloat = 0
var maxvalue : CGFloat = 1
var value : CGFloat = 0.5{
didSet{
if value > maxvalue{
value = 1
}else if value < minvalue{
value = 0
}
self.setNeedsLayout()
}
}
//创建对象
var delegate : sliderDelegate!
var sliderview = UIView()
//构造函数
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.blueColor()
sliderview.backgroundColor = UIColor.brownColor()
self.addSubview(sliderview)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = UIColor.blueColor()
sliderview.backgroundColor = UIColor.brownColor()
self.addSubview(sliderview)
}
//定义触摸移动函数
func Movesliderview(touches: NSSet){
let touch = touches.anyObject() as! UITouch
let location = touch.locationInView(self)
value = (location.x / self.frame.size.width) * (maxvalue-minvalue) + minvalue
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
print("bagan")
Movesliderview(touches)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
print("moved")
Movesliderview(touches)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
print("end")
//1.通过闭包实现
// if didchange != nil{
// didchange(self)
// }
//2.通过sendActionsForContrloEvents实现
// self.sendActionsForControlEvents(.ValueChanged)
//3.通过协议实现
if delegate != nil{
delegate.sliderdelegate(self)
}
}
override func layoutSubviews() {
super.layoutSubviews()
let width = (value-minvalue)*self.frame.size.width/(maxvalue-minvalue)
let rect = CGRect(x: 0, y: 0, width: width, height: self.frame.size.height)
sliderview.frame = rect
}
}