前言
如果想自己实现下拉刷新控件,可以参考一下以下的思路,从李明杰老师上学的
先说一下使用的场景,一般都是自定义tableView的headerView,然后通过各种方法让其实现有下拉刷新的功能
- 全局变量
@property (nonatomic, weak) UILabel *label;
- 写成一个方法(先制作headerView)
- (void)setupRefresh{
UIView *headerView = [[UIView alloc]init];
headerView.height = 50;
headerView.width = self.tableView.width;
headerView.y = -50;
[self.tableView addSubview:headerView];
UILabel *label = [[UILabel alloc]init];
label.text = @"下拉可以刷新";
[label sizeToFit];
label.center = CGPointMake(headerView.width * 0.5, headerView.height * 0.5);
[headerView addSubview:label];
self.label = label;
}
- 监听scrollView的拖拽(根据拖拽程度判断该执行什么)
// 高度直接写死了,如果有需要的同学换一下高度就可以
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
if (scrollView.contentInset.top == 149) {
return;
}
if (scrollView.contentOffset.y <= -149.0) {
self.label.text = @"松开立即刷新";
}else {
self.label.text = @"下拉可以刷新";
}
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
if (scrollView.contentOffset.y <= - 149.0) { // 进入下拉刷新状态
self.label.text = @"正在刷新";
[UIView animateWithDuration:0.5 animations:^{
UIEdgeInsets inset = scrollView.contentInset;
inset.top = 149;
scrollView.contentInset = inset;
}];
// 模拟一下刷新,延迟2秒
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[UIView animateWithDuration:0.5 animations:^{
UIEdgeInsets inset = scrollView.contentInset;
inset.top = 99;
scrollView.contentInset = inset;
}];
});
}
}