美文网首页
分析MJRefresh框架,并模拟下拉刷新

分析MJRefresh框架,并模拟下拉刷新

作者: 简_爱SimpleLove | 来源:发表于2017-05-21 02:30 被阅读48次

分析:MJRefresh框架主要使用了分层的设计思想,基类和很多子类,每个类做什么都分工明确,所以也就使得可扩展性很强。
基类所负责的事情主要是:

  • 开始刷新、结束刷新、并用KVO来进行监听
  • prepare:来添加子view、修改属性
  • placeSubViews:修改子view的frame
  • setState:通过设置刷新状态来调用刷新方法

由于这些方法子类也会更改,所以将方法公开,让子类能够继承

注意1

在给父类写分类的时候由于,分类可以写属性的方法,但是无法写实例变量,所以用运行时的方法给scrollView增加一个实例变量,如下:

#import <UIKit/UIKit.h>
#import "EOCRefreshBaseHeader.h"

@interface UIScrollView (EOCRefresh)
@property(nonatomic, strong)EOCRefreshBaseHeader *eocHeader;
@end
#import "UIScrollView+EOCRefresh.h"
#import <objc/runtime.h>

@implementation UIScrollView (EOCRefresh)

const static char EOCHeaderKey = 'H';

- (void)setEocHeader:(EOCRefreshBaseHeader *)eocHeader {
    
    if (eocHeader != self.eocHeader) {
        //删除旧的,添加新的header
        [self.eocHeader removeFromSuperview];
        [self insertSubview:eocHeader atIndex:0];
        //分类可以写属性的方法,但是无法写实例变量,所以用运行时的方法给scrollView增加一个实例变量
        objc_setAssociatedObject(self, &EOCHeaderKey, eocHeader, OBJC_ASSOCIATION_ASSIGN);
    }
}

- (EOCRefreshBaseHeader *)eocHeader {
    return objc_getAssociatedObject(self, &EOCHeaderKey);
}
@end

只有写了实例变量,我们才能

self.table.eocHeader = [EOCRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"header refreshing");
    }];

这样的进行使用。

上面在将header加到tableView上面时,一共做了三件事情

  • 创建header
  • 加到superView
  • 监听offset的改变,做出操作(kvo达成)
注意2

我们一般把控件的初始化方法写在initWithFrame方法中,因为调用init方法的时候,它会来调用initWithFrame。

- (instancetype)initWithFrame:(CGRect)frame {
    //initWithFrame 你调用init方法的时候,它会来调用initWithFrame
    if (self = [super initWithFrame:frame]) {
        [self prepare];
        self.state = EOCRefreshStateIdle;// 初始化默认状态,即闲置状态header是在屏幕外面的
    }
    return self;
}

比较简单的控件,我们可以使用autoresizingMask来适配,譬如这里self.autoresizingMask = UIViewAutoresizingFlexibleWidth;//autoSizing,self的宽度它会跟着superView一起改变

注意3
  1. 监听要放在基类的willMoveToSuperview方法中,并且当header被不同的tableView添加的时候,要移除原来的监听。当多个tableView创建多个header来监听。
  2. 这个时候还没有设置控件的frame,还可以在这里面设置它的一些固定的属性:宽和X值,而高度因头部控件和尾部控件的高度不一样,所以先不进行设置。
-(void)willMoveToSuperview:(UIView *)newSuperview {
    //当self被添加到superView的时候,调用
    if (newSuperview && [newSuperview isKindOfClass:[UIScrollView class]]) {
        
        //非空,而且是UIScrollView
        //同一个header被不同的table来添加的时候
        [self.superview removeObserver:self forKeyPath:@"contentOffset"];
        
        self.scrollView = (UIScrollView *)newSuperview;
        self.originalScrollInsets = self.scrollView.contentInset;
        //控件还没有设置frame
        self.eoc_x = 0.f;
        self.eoc_w = self.scrollView.eoc_w;
        //footer和header都继承,这两者的高度是不一样
        [newSuperview addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
    }
}
注意4

当有子控件需要初始化时,要将父控件写为[[self alloc] init],这样才会哪个子类调用就初始化成哪个子类。

+ (instancetype)headerWithRefreshingBlock:(eocRefreshingBlock)block {
    EOCRefreshBaseHeader *header = [[self alloc] init];
    header.refreshingBlock = block;
    return header;
}
注意5

往下拉的时候yOffset是为负数。并且header它能够悬停:是通过contentInset来改变的,改变它的可见范围。

#import "EOCRefreshBaseHeader.h"

@implementation EOCRefreshBaseHeader

+ (instancetype)headerWithRefreshingBlock:(eocRefreshingBlock)block {
    EOCRefreshBaseHeader *header = [[self alloc] init];
    header.refreshingBlock = block;
    return header;
}
- (void)prepare {
    [super prepare];
    //设置高度
    self.eoc_h = 50.f;
    // 不能再这里设置宽度,因为这个时候scrollView还为nil,因为alloc要比willMoveToSuperview先调用
//    self.eoc_w = self.scrollView.eoc_w;

}

- (void)placeSubviews {
    
    [super placeSubviews];
    //设置y坐标,跟superView紧密相关  placeSubviews写在layoutSubviews中的,所以要在这里面设置Y值
    self.eoc_y = -self.eoc_h-self.originalScrollInsets.top;
    
}

- (void)scrollOffsetDidChange:(NSDictionary *)change {
    [super scrollOffsetDidChange:change];
    // 我们的header它能够悬停:contentInset来改变的
    //1、正在refreshing, 你滑动的时候,contentInset是改变的,因为你滑动到了临界点 进行刷新的时候,有EOCRefreshStateIdle和EOCRefreshStateRefreshing两种状态,两种状态的contentInset不同的
    CGFloat yOffset = self.scrollView.eoc_offsetY;
    CGFloat boundaryOffset = self.originalScrollInsets.top+self.eoc_h;  // 临界值
    CGFloat pullingPercent = -yOffset/boundaryOffset;
    
    if (self.state == EOCRefreshStateRefreshing) {
         self.alpha = 1.f;   //如果不写它的话,刷新的情况下,alpha值会渐变的,实际效果是在refresh状态下不渐变
        //往下拉的时候,yOffset是为负的,下拉的距离大于临界值就是刷新,InsetTop为临界值,不然就是下拉的距离
        CGFloat finalInsetTop = (-yOffset > boundaryOffset)?boundaryOffset:-yOffset;
        self.scrollView.eoc_insetT = finalInsetTop;
    }

    if (self.scrollView.dragging) {  //正在滑动
        self.alpha = pullingPercent;   // 往下拉的时候,颜色渐变
        if (self.state == EOCRefreshStateIdle && -yOffset > boundaryOffset) {
            //处于闲置状态、而且大于边界值
            self.state = EOCRefreshStatePulling;   //设置为正在拉的状态
        } else if (self.state == EOCRefreshStatePulling && -yOffset < boundaryOffset) {
            self.state = EOCRefreshStateIdle;   // 设置为闲置状态
        }
    } else {  //松手了
        if (self.state == EOCRefreshStatePulling) {
            self.state = EOCRefreshStateRefreshing;  // 设置为刷新状态
        } else if (pullingPercent < 1) {
            self.alpha = pullingPercent;  // 小于1,即还没有到刷新状态的时候,header回去的时候也是渐变
        }
    }
}

- (void)setState:(EOCRefreshState)state {
    [super setState:state];
    if (state == EOCRefreshStateRefreshing) {
        [UIView animateWithDuration:0.4f animations:^{
            self.scrollView.eoc_insetT = self.originalScrollInsets.top+self.eoc_h;
            //因为弹簧效果,当往下拉,松手后往上弹得时候,会使有yOffset小于临界值,从而调用上面的  CGFloat finalInsetTop = (-yOffset > boundaryOffset)?boundaryOffset:-yOffset; self.scrollView.eoc_insetT = finalInsetTop;  这句代码使header被隐藏了一部分,所以要加上下面这句代码
            self.scrollView.eoc_offsetY = -(self.originalScrollInsets.top+self.eoc_h);
        }];
        //刷新block
        [self beginRefresh];
    } else if (state == EOCRefreshStateIdle) {
       [UIView animateWithDuration:0.4f animations:^{
        self.scrollView.contentInset = self.originalScrollInsets;
       }];
    }
    
}
@end
注意6

访问bundle中的image资源方法

   _arrowImageView =
 [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:[[NSBundle bundleWithPath:[[NSBundle bundleForClass:[EOCRefreshNormalHeader class]] pathForResource:@"MJRefresh" ofType:@"bundle"]] pathForResource:@"arrow@2x" ofType:@"png"]]];

从MJRefresh.bundle中获取图片到EOCRefreshNormalHeader类中

注意7

如果一个控件经常用到,而且属性都一样,可以写成它的分类,并且放在基类里面, 如下面的label:


#import <UIKit/UIKit.h>

@interface EOCRefreshBaseView : UIView

typedef NS_ENUM(NSInteger, EOCRefreshState) {
    EOCRefreshStateIdle = 1,        //闲置状态
    EOCRefreshStatePulling,         //释放就刷新的状态
    EOCRefreshStateRefreshing,      //正在刷新状态
};

typedef void (^eocRefreshingBlock)();

//刷新数据的block
@property(nonatomic, strong)eocRefreshingBlock refreshingBlock;
@property(nonatomic, strong)UIScrollView *scrollView;
@property(nonatomic, assign)UIEdgeInsets originalScrollInsets;
@property(nonatomic, assign)EOCRefreshState state;

- (void)prepare;  // 来添加子view、修改属性
- (void)placeSubviews;  // 修改子view的frame
- (void)endRefresh;  //结束刷新
- (void)beginRefresh;  //开始刷新
- (void)scrollOffsetDidChange:(NSDictionary *)change;

@end

@interface UILabel (EOCLabel)
+ (instancetype)eocLabel;
- (CGFloat)textWidth;

@end
#import "EOCRefreshBaseView.h"
@interface EOCRefreshBaseView ()
@end
@implementation EOCRefreshBaseView
//head加进来:创建header、加到superView、监听offset的改变,做出操作(kvo达成)

-(instancetype)initWithFrame:(CGRect)frame {
    //initWithFrame 你调用init方法的时候,它会来调用initWithFrame
    if (self = [super initWithFrame:frame]) {
        [self prepare];
        self.state = EOCRefreshStateIdle;  // 初始化默认状态,即闲置状态header是在屏幕外面的
    }
    return self;
}

-(void)prepare {
    self.backgroundColor = [UIColor redColor];
    self.autoresizingMask = UIViewAutoresizingFlexibleWidth;//autoSizing,self的宽度它会跟着superView一起改变
}

-(void)layoutSubviews {
    
    [super layoutSubviews];
    //修改子view的frame
    [self placeSubviews];
}

-(void)placeSubviews {}

-(void)willMoveToSuperview:(UIView *)newSuperview {
    //当self被添加到superView的时候,调用
    if (newSuperview && [newSuperview isKindOfClass:[UIScrollView class]]) {
        
        //非空,而且是UIScrollView
        //同一个header被不同的table来添加的时候
        [self.superview removeObserver:self forKeyPath:@"contentOffset"];
        
        self.scrollView = (UIScrollView *)newSuperview;
        self.originalScrollInsets = self.scrollView.contentInset;
        //控件还没有设置frame
        self.eoc_x = 0.f;
        self.eoc_w = self.scrollView.eoc_w;
        //footer和header都继承,这两者的高度是不一样
        [newSuperview addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
    }
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"contentOffset"]) {
        [self scrollOffsetDidChange:change];
    }
}

-(void)scrollOffsetDidChange:(NSDictionary *)change {}

-(void)setState:(EOCRefreshState)state {
    _state = state;
    
}

-(void)endRefresh {
    //把当前的时间存起来
    [[NSUserDefaults standardUserDefaults]setObject:[NSDate date] forKey:@"lastUpdateDate"];
    self.state = EOCRefreshStateIdle;
    
}

-(void)beginRefresh {
    
    if (_refreshingBlock) {
        _refreshingBlock();
    }
}
@end

@implementation UILabel (EOCLabel)

+ (instancetype)eocLabel {
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:14.f];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor blueColor];
    label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    label.textAlignment = NSTextAlignmentCenter;
    return label;
}

- (CGFloat)textWidth {
    
    NSString *text = self.text;
    UIFont *font = self.font;
    CGSize textSize = [text sizeWithAttributes:@{NSFontAttributeName:font}];
    return textSize.width;
    
}
@end
注意8

箭头旋转的时候,如果要实现顺时针旋转下来,逆时针旋转回去,需要将其中一个设置为CGAffineTransformMakeRotation(0.00001-M_PI),用0.00001减去M_PI,因为旋转的时候遵循下面的三点

  1. 基本按照最短路径来,如果顺时针、逆时针角度一样的,按顺时针来
  2. CGAffineTransformMakeRotation会根据最初始的值来计算角度
  3. 角度为正,顺时针;角度为负,逆时针

所以当用0.00001减去M_PI的时候,那么来的路径变短了,所以就原路返回了

- (void)setState:(EOCRefreshState)state {
    
    [super setState:state];
    //1、刷新的时候,箭头要隐藏,loadview显示; 2、pulling的时候,箭头的方向改变
    if (state == EOCRefreshStateIdle) {
        [UIView animateWithDuration:0.4f animations:^{
            self.loadView.alpha = 1.f;
            _arrowImageView.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
//            self.loadView.hidden = YES;
            self.loadView.alpha = 0.f;
            [self.loadView stopAnimating];
            _arrowImageView.alpha = 1.f;
            
        }];
    } else if (state == EOCRefreshStatePulling) {
        
        [UIView animateWithDuration:0.4f animations:^{
            _arrowImageView.transform = CGAffineTransformMakeRotation(0.0001-M_PI);
            
        }];
        
    } else if (state == EOCRefreshStateRefreshing) {
        _arrowImageView.alpha = 0.f;
//        _loadView.hidden = NO;
        _loadView.alpha = 0.f;
        [_loadView startAnimating];
        
    }
    
}

相关文章

网友评论

      本文标题:分析MJRefresh框架,并模拟下拉刷新

      本文链接:https://www.haomeiwen.com/subject/koupxxtx.html