实现简易版的上下拉刷新控件XDRefresh

XDRefresh

开发的时候经常用到上下拉刷新控件,因为项目只是需要实现简单的菊花样式的刷新动画,所以自己封装了一个简易版上下拉刷新控件,到时未来再拓展出可以自定义的刷新控件。

效果图

使用

1
2
3
4
5
6
7
8
9
10
11
12
#import "KitRefresh.h"
...
KitRefreshHeader *_header;
KitRefreshFooter *_footer;

_header =  [KitRefreshHeader headerOfScrollView:tableView withRefreshingBlock:^{
     //下拉刷新回调
    }];
    
_footer = [KitRefreshFooter footerOfScrollView:tableView withRefreshingBlock:^{
        //上拉刷新回调
    }];

实现原理

通过观察scrollview的contentOffset属性的变化来进行处理。
给出一段KVO处理,具体实现大家可以看源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *,id> *)change
                       context:(void *)context {
    if ([keyPath isEqualToString:@"contentOffset"]) {
        _contentHeight = _scrollView.contentSize.height;
        //拉伸状态
        if (_scrollView.isDragging) {
            CGFloat currentPosition = _scrollView.contentOffset.y;
            
            if (!_isRefreshing) {
                [UIView animateWithDuration:0.3f animations:^{
                    //下拉过程超过_headerHeight*1.5
                    if (currentPosition < -_headerHeight* 1.5 ) {
                        _statusLabel.text       = _releaseText;
                        _arrowView.transform    = CGAffineTransformMakeRotation(M_PI);
                    }else {
                        //上拉
                        if (currentPosition - _lastPosition > 5) {
                            _lastPosition = currentPosition;
                            _statusLabel.text = _pulldownText;
                            _arrowView.transform = CGAffineTransformMakeRotation(M_PI*2);
                            //下拉不超过_headerHeight*1.5
                        }else if(_lastPosition - currentPosition > 5) {
                            _lastPosition = currentPosition;
                        }
                    }
                }];
            }
            
        }else {
            //松开手时
            if ([_statusLabel.text isEqualToString:_releaseText]) {
                [self beginRefreshing];
            }
        }

    }
}

源码地址

https://github.com/caixindong/XDRefresh/tree/master/XDRefresh 大家觉得喜欢就赏个star,有什么问题可以issue我或者在评论指出,相互学习

Comments