- 自定義下拉刷新控件分析
- 該控件繼承誰 - UIControl
- 該控件貼在誰身上 tableView
- 該控件Y軸 == -控件的高度 - 分析狀態(tài)
- 如果正在拖動tableView 沒有松手
- 正常 contentOffSet.y > -(自定義刷新控件高度+64) && 當前狀態(tài)為下拉中
- 下拉中 contentOffSet.y <= -(自定義刷新控件高度+64) && 當前狀態(tài)為正常
- 如果停止拖動 并松手 而且控件的狀態(tài)為下拉中
- 刷新中
封裝代碼:
import UIKit
// 自定義刷新控件的高度
let REFRESH_HEIGHT: CGFloat = 50
// 設(shè)置自定義刷新控件的背景色
let REFRESH_BACKGROUND_COLOR: UIColor = UIColor.orangeColor()
// 屏幕寬度
let SCREEN_WIDTH = UIScreen.mainScreen().bounds.width
// 自定義刷新控件文字狀態(tài)字體大小
let STATUS_LABEL_FONT_SIZE: CGFloat = 15
// 自定義刷新控件文字字體顏色
let STATUS_LABEL_FONT_COLOR: UIColor = UIColor.purpleColor()
// 刷新控件的狀態(tài)
enum JSRefreshType: Int {
case Normal = 0 // 正常
case Pulling = 1 // 下拉中
case Refreshing = 2 // 刷新中
}
class JSRefresh: UIControl {
// 被觀察對象
var scrollerView: UIScrollView?
// MARK: - 懶加載控件
private lazy var statusLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFontOfSize(STATUS_LABEL_FONT_SIZE)
label.textColor = STATUS_LABEL_FONT_COLOR
label.textAlignment = .Center
return label
}()
// 記錄刷新控件狀態(tài),初始為正常狀態(tài)
var refreshStatus: JSRefreshType = .Normal{
didSet{
switch refreshStatus {
case .Normal:
statusLabel.text = "\(refreshStatus)"
//如果上一個狀態(tài)為刷新中 讓自定義控件的上方間距恢復(fù)
if oldValue == .Refreshing {
UIView.animateWithDuration(0.25, animations: {
self.scrollerView?.contentInset.top -= REFRESH_HEIGHT
})
}
case .Pulling:
statusLabel.text = "\(refreshStatus)"
case .Refreshing:
statusLabel.text = "\(refreshStatus)"
//刷新中狀態(tài)讓自定義刷新控件保留顯示
UIView.animateWithDuration(0.25, animations: {
self.scrollerView?.contentInset.top += REFRESH_HEIGHT
}, completion: { (finished) in
self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
})
}
}
}
override init(frame: CGRect) {
super.init(frame: CGRect(x: 0, y: -REFRESH_HEIGHT, width: SCREEN_WIDTH, height: REFRESH_HEIGHT))
// 設(shè)置視圖
setupUI()
}
// MARK: - 設(shè)置視圖
private func setupUI () {
// 設(shè)置背景色
backgroundColor = REFRESH_BACKGROUND_COLOR
// 添加控件
addSubview(statusLabel)
// 添加約束
statusLabel.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: statusLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: statusLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
}
// MARK: - 監(jiān)聽該類將要添加到哪個父控件上
override func willMoveToSuperview(newSuperview: UIView?) {
/*
這里需要監(jiān)測父控件的ContentOffSet判斷狀態(tài)
因為其控制器可能會使用TableView的代理方法,代理為一對一,考慮到封裝性,不推薦使用代理,所以這里使用KVO
原因:如果在這里將拿到的TableView的代理設(shè)置給了自定義控件,外界將無法使用TableView的代理
KVO的使用基本上都是三步:
1.注冊觀察者
addObserver:forKeyPath:options:context:
2.觀察者中實現(xiàn)
observeValueForKeyPath:ofObject:change:context:
3.移除觀察者
removeObserver:forKeyPath:
*/
// 判斷是否有值,是否可以滾動
guard let scrollerView = newSuperview as? UIScrollView else {
return
}
self.scrollerView = scrollerView
// 注冊觀察者
scrollerView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
}
// 觀察者實現(xiàn)
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
// 獲取所監(jiān)聽的scrollView的Y軸偏移量
let contentOffSetY = self.scrollerView!.contentOffset.y
//添加導(dǎo)航控制器后,scrollView會自動向下偏移64 (IOS 7 以后)
let contentInsetTop = self.scrollerView!.contentInset.top
// 判斷ScrollView是否正在拖動
if scrollerView!.dragging {
// 如果 scrollerView!.dragging == true 代表當前正在拖動ScrollView
if contentOffSetY > -(REFRESH_HEIGHT+ contentInsetTop) && refreshStatus == .Pulling {
// contentOffSet.y > -(自定義刷新控件高度+ contentInsetTop) && 當前狀態(tài)為下拉中 --> 正常狀態(tài)
refreshStatus = .Normal
} else if contentOffSetY <= -(REFRESH_HEIGHT+ contentInsetTop) && refreshStatus == .Normal {
// contentOffSet.y <= -(自定義刷新控件高度+ contentInsetTop) && 當前狀態(tài)為正常 --> 下拉狀態(tài)
refreshStatus = .Pulling
}
// 未拖動ScrollView時
} else {
// 停止拖動并松手,而且狀態(tài)為下拉中 --> 刷新
if refreshStatus == .Pulling {
refreshStatus = .Refreshing
}
}
}
// MARK: - 結(jié)束刷新
func endRefreshing() -> Void {
// 將狀態(tài)改為正常
refreshStatus = .Normal
}
deinit{
// 移除觀察者
self.scrollerView?.removeObserver(self, forKeyPath: "contentOffset")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
使用演示:
import UIKit
class ViewController: UITableViewController {
var dataArr: [AnyObject] = {
let arr = [1,2,3,4,5]
return arr
}() //模擬數(shù)據(jù)
let refresh: JSRefresh = JSRefresh() //自定義刷新控件
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "id")
//設(shè)置視圖
setupUI()
}
private func setupUI () {
//添加控件
tableView.addSubview(refresh)
refresh.addTarget(self, action: #selector(refreshAction), forControlEvents: UIControlEvents.ValueChanged)
}
@objc private func refreshAction () {
// 模擬網(wǎng)絡(luò)延遲
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue()) {
// 請求數(shù)據(jù)
self.dataArr += self.dataArr
self.tableView.reloadData()
// 結(jié)束刷新
self.refresh.endRefreshing()
}
}
}
extension ViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataArr.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("id", forIndexPath: indexPath)
cell.textLabel?.text = "\(indexPath.row)"
return cell
}
}