(Target-Action,協(xié)議,閉包)
簡(jiǎn)單控件用閉包
復(fù)雜控件用協(xié)議
新建一個(gè)類ProtocolSlider
//協(xié)議的優(yōu)點(diǎn):明確
//協(xié)議的缺點(diǎn):復(fù)雜,步驟太多
//如果有optional方法,必須使用@objc
@objc protocol ProtocolSliderDelegate {
optional func didChange(slider: ProtocolSlider類名)
}
class ProtocolSlider: UIView {
let trackView = UIView()
// 用于關(guān)聯(lián)兩個(gè)對(duì)象(控件與需要獲取事件的對(duì)象)
var delegate: ProtocolSliderDelegate!
// 如果使用閉包,定義一個(gè)閉包
// var didChange: ((ProtocolSlider) -> Void)!
var minValue: CGFloat = 0
var maxValue: CGFloat = 1
var currentValue: CGFloat = 0.5 {
didSet {
// self.sendActionsForControlEvents(.ValueChanged)
self.setNeedsLayout()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(trackView)
self.backgroundColor = UIColor.cyanColor()
trackView.backgroundColor = UIColor.redColor()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.addSubview(trackView)
self.backgroundColor = UIColor.cyanColor()
trackView.backgroundColor = UIColor.redColor()
}
func moveTrack(touches: NSSet) {
let touch = touches.anyObject() as! UITouch
let location = touch.locationInView(self)
currentValue = (location.x / self.frame.size.width) * (maxValue - minValue) +minValue
}
//開(kāi)始觸摸
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// print("begin")
moveTrack(touches)
}
//移動(dòng)
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
// print("continue")
moveTrack(touches)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
// print("end")
//觸發(fā)事件
// self.sendActionsForControlEvents(.ValueChanged)
// 實(shí)現(xiàn)閉包
// 1. 如果使用協(xié)議,需要確保delegate是否為空
// 2. 如果方法為optional,需要確保方法是否實(shí)現(xiàn)
// if delegate != nil {
// if delegate.didChange != nil {
// delegate.didChange!(self)
// }
// }
if didChange != nil {
didChange(self)
}
}
override func layoutSubviews() {
super.layoutSubviews()
let width = (currentValue - minValue) * self.frame.size.width / (maxValue -minValue)
let rect = CGRect(x: 0, y: 0, width: width, height: self.frame.size.height)
trackView.frame = rect
}
}
在ViewControl中實(shí)現(xiàn)協(xié)議
import UIKit
class ViewController: UIViewController, ProtocolSliderDelegate, UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
//UIControl
//Target-Action
let slider = ProtocolSlider(frame: CGRect(x: 100, y: 100, width: 200, height:50))
// UIControl addTarget 實(shí)現(xiàn)方法
// slider.addTarget(self, action: #selector(didChange(_:)), forControlEvents: .ValueChanged)
// slider.delegate = self
// 調(diào)用閉包
// slider.didChange = {
// sender in
// print(sender.currentValue)
// }
//函數(shù):特殊閉包
//閉包:匿名函數(shù)
slider.didChange = didChange 協(xié)議實(shí)現(xiàn)方法
self.view.addSubview(slider) 協(xié)議實(shí)現(xiàn)方法
}
func didChange(sender: ProtocolSlider) {
print(sender.currentValue)
}
}