前言
网上有着不少关于ios的刷新控件的框架,其中比较出名的是MJRefresh,笔者也经常在项目中使用到。这次自己也尝试着写了一个下拉刷新控件。
效果图
分析
一、监听滚动
首先,刷新控件当然是要添加在tableView上的,并且我们需要监听tableView的滚动情况,来判断是否执行刷新操作。关于监听ttableView的滚动,我们一开始当时是想到tableView的代理方法,可是这样的话,这控件太不具备移植性了。于是采用另一种方案,KVO。
///添加监听
- (void)willMoveToSuperview:(UIView *)newSuperview {
if ([newSuperview isKindOfClass:[UIScrollView class]]) {
self.mySuperview = (UIScrollView *)newSuperview;
[self.mySuperview addObserver:self forKeyPath:@"contentOffset" options:0 context:nil];
}
}
二、控件的状态
刷新一共分为下拉刷新,释放刷新,正在刷新三种状态。
typedef enum : NSUInteger {
OCPullDownRefreshViewStatusNormal, //下拉刷新
OCPullDownRefreshViewStatusPulling, //释放刷新
OCPullDownRefreshViewStatusRefresh, //正在刷新
} OCPullDownRefreshViewStatus;
此外,还需要分是否拖拽中,偏移量,判断状态。
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
//是否在拖拽中
if (self.mySuperview.isDragging) {
//下拉刷新: offy > -124
if (self.currentStatus == OCPullDownRefreshViewStatusPulling && self.mySuperview.contentOffset.y > -124) {
self.currentStatus = OCPullDownRefreshViewStatusNormal;
}else if (self.currentStatus == OCPullDownRefreshViewStatusNormal && self.mySuperview.contentOffset.y < -124 ) {
//释放刷新
self.currentStatus = OCPullDownRefreshViewStatusPulling;
}
}else {
//正在刷新
if (self.currentStatus == OCPullDownRefreshViewStatusPulling && self.mySuperview.contentOffset.y < -124) {
self.currentStatus = OCPullDownRefreshViewStatusRefresh;
}
}
}
总结
最关键的就是判断当前控件的状态,状态判断好了,想做什么只要找好对应的状态执行方法即可。