(Target-Action,協議,閉包)
簡單控件用閉包
復雜控件用協議
新建一個類ProtocolSlider
//協議的優點:明確
//協議的缺點:復雜,步驟太多
//如果有optional方法,必須使用@objc
@objc protocol ProtocolSliderDelegate {
optional func didChange(slider: ProtocolSlider類名)
}
class ProtocolSlider: UIView {
let trackView = UIView()
// 用于關聯兩個對象(控件與需要獲取事件的對象)
var delegate: ProtocolSliderDelegate!
// 如果使用閉包,定義一個閉包
// 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
}
//開始觸摸
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// print("begin")
moveTrack(touches)
}
//移動
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
// print("continue")
moveTrack(touches)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
// print("end")
//觸發事件
// self.sendActionsForControlEvents(.ValueChanged)
// 實現閉包
// 1. 如果使用協議,需要確保delegate是否為空
// 2. 如果方法為optional,需要確保方法是否實現
// 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中實現協議
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 實現方法
// slider.addTarget(self, action: #selector(didChange(_:)), forControlEvents: .ValueChanged)
// slider.delegate = self
// 調用閉包
// slider.didChange = {
// sender in
// print(sender.currentValue)
// }
//函數:特殊閉包
//閉包:匿名函數
slider.didChange = didChange 協議實現方法
self.view.addSubview(slider) 協議實現方法
}
func didChange(sender: ProtocolSlider) {
print(sender.currentValue)
}
}