继续阅读关于UI方面的比较好的第三方库MJRefresh
这个库整体难度不大,但是作者的思路很好很清晰,核心是使用基类MJRefreshComponent
来做一些基本的设定,然后通过继承的方式,让MJRefreshHeader
和MJRefreshFooter
分别具备下拉刷新和上拉加载的功能,然后你自定义私人定制的话,那么久继续继承,在此基础上修改UI和逻辑操作。
MJRefreshComponent
代码逻辑
代码逻辑非常清晰,自上而下
1.设置刷新控件的状态
2.处理刷新事件的回调
3.设置刷新事件的属性(target,action,block)
4.刷新状态控制的函数
5.交给子类去实现的函数
设置刷新控件的状态
/** 刷新控件的状态 */
typedef NS_ENUM(NSInteger, MJRefreshState) {
/** 普通闲置状态 */
MJRefreshStateIdle = 1,
/** 松开就可以进行刷新的状态 */
MJRefreshStatePulling,
/** 正在刷新中的状态 */
MJRefreshStateRefreshing,
/** 即将刷新的状态 */
MJRefreshStateWillRefresh,
/** 所有数据加载完毕,没有更多的数据了 */
MJRefreshStateNoMoreData
};
代码规范要这么写,不然外面拿不到提示的
处理刷新事件的回调
/** 进入刷新状态的回调 */
typedef void (^MJRefreshComponentRefreshingBlock)();
/** 开始刷新后的回调(进入刷新状态后的回调) */
typedef void (^MJRefreshComponentbeginRefreshingCompletionBlock)();
/** 结束刷新后的回调 */
typedef void (^MJRefreshComponentEndRefreshingCompletionBlock)();
设置刷新事件的属性
/** 正在刷新的回调 */
@property (copy, nonatomic) MJRefreshComponentRefreshingBlock refreshingBlock;
/** 开始刷新后的回调(进入刷新状态后的回调) */
@property (copy, nonatomic) MJRefreshComponentbeginRefreshingCompletionBlock beginRefreshingCompletionBlock;
/** 结束刷新的回调 */
@property (copy, nonatomic) MJRefreshComponentEndRefreshingCompletionBlock endRefreshingCompletionBlock;
刷新状态控制的函数
/** 进入刷新状态 */
- (void)beginRefreshing;
- (void)beginRefreshingWithCompletionBlock:(void (^)())completionBlock;
/** 结束刷新状态 */
- (void)endRefreshing;
- (void)endRefreshingWithCompletionBlock:(void (^)())completionBlock;
/** 是否正在刷新 */
- (BOOL)isRefreshing;
/** 刷新状态 一般交给子类内部实现 */
@property (assign, nonatomic) MJRefreshState state;
交给子类去实现的函数
/** 初始化 */
- (void)prepare NS_REQUIRES_SUPER;
/** 摆放子控件frame */
- (void)placeSubviews NS_REQUIRES_SUPER;
/** 当scrollView的contentOffset发生改变的时候调用 */
- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change NS_REQUIRES_SUPER;
/** 当scrollView的contentSize发生改变的时候调用 */
- (void)scrollViewContentSizeDidChange:(NSDictionary *)change NS_REQUIRES_SUPER;
/** 当scrollView的拖拽状态发生改变的时候调用 */
- (void)scrollViewPanStateDidChange:(NSDictionary *)change NS_REQUIRES_SUPER;
核心代码
添加监听
通过监听ContentOffset和ContentSize的改变,以及手势状态的变化,从而来回调事件,交给子类来做一些自定义的处理
#pragma mark - KVO监听
- (void)addObservers
{
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[self.scrollView addObserver:self forKeyPath:MJRefreshKeyPathContentOffset options:options context:nil];
[self.scrollView addObserver:self forKeyPath:MJRefreshKeyPathContentSize options:options context:nil];
self.pan = self.scrollView.panGestureRecognizer;
[self.pan addObserver:self forKeyPath:MJRefreshKeyPathPanState options:options context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
// 遇到这些情况就直接返回
if (!self.userInteractionEnabled) return;
// 这个就算看不见也需要处理
if ([keyPath isEqualToString:MJRefreshKeyPathContentSize]) {
[self scrollViewContentSizeDidChange:change];
}
// 看不见
if (self.hidden) return;
if ([keyPath isEqualToString:MJRefreshKeyPathContentOffset]) {
[self scrollViewContentOffsetDidChange:change];
} else if ([keyPath isEqualToString:MJRefreshKeyPathPanState]) {
[self scrollViewPanStateDidChange:change];
}
}
- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change{
NSLog(@"scrollViewContentOffsetDidChange change = %@",change);
}
- (void)scrollViewContentSizeDidChange:(NSDictionary *)change{
NSLog(@"scrollViewContentSizeDidChange change = %@",change);
}
- (void)scrollViewPanStateDidChange:(NSDictionary *)change{
NSLog(@"scrollViewPanStateDidChange change = %@",change);
}
刷新的代码处理
//在这边都是没有做任何代码处理,只是修改了当前状态和存储了更新开始和结束的事件回调,很显然这些事情都交给子类去做(这个思想很好,基类只做状态存储和基本数据存储,自定义的操作 全部由子类来执行,代码也很清晰,思路也很明确,good!)
#pragma mark 进入刷新状态
- (void)beginRefreshing
{
[UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{
self.alpha = 1.0;
}];
self.pullingPercent = 1.0;
// 只要正在刷新,就完全显示
if (self.window) {
self.state = MJRefreshStateRefreshing;
} else {
// 预防正在刷新中时,调用本方法使得header inset回置失败
if (self.state != MJRefreshStateRefreshing) {
self.state = MJRefreshStateWillRefresh;
// 刷新(预防从另一个控制器回到这个控制器的情况,回来要重新刷新一下)
[self setNeedsDisplay];
}
}
}
- (void)beginRefreshingWithCompletionBlock:(void (^)())completionBlock
{
self.beginRefreshingCompletionBlock = completionBlock;
[self beginRefreshing];
}
#pragma mark 结束刷新状态
- (void)endRefreshing
{
self.state = MJRefreshStateIdle;
}
- (void)endRefreshingWithCompletionBlock:(void (^)())completionBlock
{
self.endRefreshingCompletionBlock = completionBlock;
[self endRefreshing];
}
#pragma mark 是否正在刷新
- (BOOL)isRefreshing
{
return self.state == MJRefreshStateRefreshing || self.state == MJRefreshStateWillRefresh;
}
总结
MJRefreshComponent真的很基础,没有做很多复杂的操作,上拉刷新和下拉加载,其实全部都是由他的子类MJRefreshHeader和MJRefreshFooter来实现
MJRefreshHeader(继承MJRefreshComponent)
代码逻辑
代码逻辑还是很清晰,自上而下
1.创建header的方式(block,action)
2.记录header的一些属性(刷新的时间,刷新的时间的key,忽略多少scrollView的contentInset的top)
3.通过重写基类的方法和监听scrollView的变化来实现自定义的效果
创建header的方式
#pragma mark - 构造方法
+ (instancetype)headerWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock
{
MJRefreshHeader *cmp = [[self alloc] init];
cmp.refreshingBlock = refreshingBlock;
return cmp;
}
+ (instancetype)headerWithRefreshingTarget:(id)target refreshingAction:(SEL)action
{
MJRefreshHeader *cmp = [[self alloc] init];
[cmp setRefreshingTarget:target refreshingAction:action];
return cmp;
}
覆盖父类的方法(核心)
- (void)prepare
{
[super prepare];
// 设置key
self.lastUpdatedTimeKey = MJRefreshHeaderLastUpdatedTimeKey;
// 设置高度
self.mj_h = MJRefreshHeaderHeight;
}
//调用后,会调用基类的layoutSubviews方法(也就是自己子类先排列好位置,再更新基类的位置)
- (void)placeSubviews
{
[super placeSubviews];
// 设置y值(当自己的高度发生改变了,肯定要重新调整Y值,所以放到placeSubviews方法中设置y值)
self.mj_y = - self.mj_h - self.ignoredScrollViewContentInsetTop;
}
- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change
{
[super scrollViewContentOffsetDidChange:change];
// 在刷新的refreshing状态
if (self.state == MJRefreshStateRefreshing) {
if (self.window == nil) return;
// sectionheader停留解决
//- self.scrollView.mj_offsetY:-(-54-64)= 118 : 刷新的时候,偏移量是不动的。偏移量 = 状态栏 + 导航栏 + header的高度
//_scrollViewOriginalInset.top:64 (状态栏20 + 导航栏44)
//insetT 取二者之间大的那一个
CGFloat insetT = - self.scrollView.mj_offsetY > _scrollViewOriginalInset.top ? - self.scrollView.mj_offsetY : _scrollViewOriginalInset.top;
//118
insetT = insetT > self.mj_h + _scrollViewOriginalInset.top ? self.mj_h + _scrollViewOriginalInset.top : insetT;
//设置contentInset
self.scrollView.mj_insetT = insetT;
// 记录刷新的时候的偏移量 -54 = 64 - 118
self.insetTDelta = _scrollViewOriginalInset.top - insetT;
return;
}
// 跳转到下一个控制器时,contentInset可能会变
_scrollViewOriginalInset = self.scrollView.contentInset;
// 当前的contentOffset
CGFloat offsetY = self.scrollView.mj_offsetY;
// 头部控件刚好出现的offsetY(-20 + -44 = -64)
CGFloat happenOffsetY = - self.scrollViewOriginalInset.top;
// 如果是向上滚动到看不见头部控件,直接返回
// >= -> >
if (offsetY > happenOffsetY) return;
// 普通 和 即将刷新 的临界点
CGFloat normal2pullingOffsetY = happenOffsetY - self.mj_h;
// 计算下拉的百分比
CGFloat pullingPercent = (happenOffsetY - offsetY) / self.mj_h;
if (self.scrollView.isDragging) { // 如果正在拖拽
//更新下拉百分比
self.pullingPercent = pullingPercent;
if (self.state == MJRefreshStateIdle && offsetY < normal2pullingOffsetY) {
// 转为即将刷新状态
self.state = MJRefreshStatePulling;
} else if (self.state == MJRefreshStatePulling && offsetY >= normal2pullingOffsetY) {
// 转为普通状态
self.state = MJRefreshStateIdle;
}
} else if (self.state == MJRefreshStatePulling) {// 即将刷新 && 手松开(当你手松开,且offsetY < normal2pullingOffsetY的时候,那么你就代表你要刷新了)
// 开始刷新
[self beginRefreshing];
} else if (pullingPercent < 1) {
//手松开的时候,不更新状态(时刻判断offsetY的取值,然后走上面两个判断是否可以刷新)
self.pullingPercent = pullingPercent;
}
//上面的思路依然很聪明,你随便拉,反正你拖动的时候,我不会去操作是否刷新,我只是时刻标记你的状态,当你停止拖动的时候,那个时候,我才会去判断你当前被标记为什么状态,从而作出正确的操作,good!
}
- (void)setState:(MJRefreshState)state
{
// 根据状态做事情,从其他状态回到常规状态
if (state == MJRefreshStateIdle) {
if (oldState != MJRefreshStateRefreshing) return;
// 保存刷新时间
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:self.lastUpdatedTimeKey];
[[NSUserDefaults standardUserDefaults] synchronize];
// 恢复inset和offset
[UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{
self.scrollView.mj_insetT += self.insetTDelta;
// 自动调整透明度
if (self.isAutomaticallyChangeAlpha) self.alpha = 0.0;
} completion:^(BOOL finished) {
self.pullingPercent = 0.0;
//执行刷新成功的回调
if (self.endRefreshingCompletionBlock) {
self.endRefreshingCompletionBlock();
}
}];
} else if (state == MJRefreshStateRefreshing) {
//从其他状态到达刷新状态
dispatch_async(dispatch_get_main_queue(), ^{
[UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{
CGFloat top = self.scrollViewOriginalInset.top + self.mj_h;
// 增加滚动区域top(设置contentInset)
self.scrollView.mj_insetT = top;
// 设置滚动位置(设置contentOffset)
[self.scrollView setContentOffset:CGPointMake(0, -top) animated:NO];
} completion:^(BOOL finished) {
//执行刷新成功的回调
[self executeRefreshingCallback];
}];
});
}
}
#pragma mark - 公共方法
- (void)endRefreshing
{
dispatch_async(dispatch_get_main_queue(), ^{
self.state = MJRefreshStateIdle;
});
}
总结
MJRefreshHeader 整体难度不大,核心的思想
1.重写prepare方法,存储时间搓,以及配置高度
2.重写placeSubviews方法,更新子控件的UI
3.重写scrollViewContentOffsetDidChange方法,从而通过更新State来实现不同的视觉效果
4.更具setState方法来更新UI,实际就是更新scrollView的contentOffset,contentInset等(这个是核心函数)
我觉得作者这样的思想很好,因为从后面的子类中,你可以看到,都是统一这样的思路,prepare做数据存储和配置,placeSubviews更新子视图控件位置,scrollViewContentOffsetDidChange代码处理,最后在setState更新UI视图。
MJRefreshFooter(继承MJRefreshComponent)
代码逻辑
MJRefreshFooter和MJRefreshComponent一样 比较抽象,没有什么核心操作,没有监听的处理,只是定义了几个常规的footer函数,由子类来实现加载的真正实现
1.创建footer的方式(block,action)
2.记录footer的属性(忽略多少scrollView的contentInset的bottom,自动根据有无数据来显示和隐藏(有数据就显示,没有数据隐藏。默认是NO))
3.配置一些footer状态切换函数
创建footer的方式
#pragma mark - 构造方法
+ (instancetype)footerWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock
{
MJRefreshFooter *cmp = [[self alloc] init];
cmp.refreshingBlock = refreshingBlock;
return cmp;
}
+ (instancetype)footerWithRefreshingTarget:(id)target refreshingAction:(SEL)action
{
MJRefreshFooter *cmp = [[self alloc] init];
[cmp setRefreshingTarget:target refreshingAction:action];
return cmp;
}
配置footer状态切换的函数
#pragma mark - 公共方法
- (void)endRefreshingWithNoMoreData
{
self.state = MJRefreshStateNoMoreData;
}
- (void)noticeNoMoreData
{
[self endRefreshingWithNoMoreData];
}
- (void)resetNoMoreData
{
self.state = MJRefreshStateIdle;
}
覆盖父类的方法(核心)
- (void)prepare
{
[super prepare];
// 设置自己的高度
self.mj_h = MJRefreshFooterHeight;
// 默认不会自动隐藏
self.automaticallyHidden = NO;
}
- (void)willMoveToSuperview:(UIView *)newSuperview
{
[super willMoveToSuperview:newSuperview];
if (newSuperview) {
// 监听scrollView数据的变化
if ([self.scrollView isKindOfClass:[UITableView class]] || [self.scrollView isKindOfClass:[UICollectionView class]]) {
[self.scrollView setMj_reloadDataBlock:^(NSInteger totalDataCount) {
//通过获取行数的大小来判断是否要隐藏footer(这个想法很好,要学习,good!)
if (self.isAutomaticallyHidden) {
self.hidden = (totalDataCount == 0);
}
}];
}
}
}
总结
MJRefreshFooter 没有做什么核心的逻辑操作,核心的思想
1.覆盖父类的方法来配置高度和根据scrollView的总体个数来判断footer是否要显示。
2.配置了一些切换加载更多的状态,
MJRefreshStateHeader(继承MJRefreshHeader)
代码逻辑
MJRefreshStateHeader主要是stateLabel和lastUpdatedTimeLabel的展示,根据state的状态改变,再改变stateLabel和lastUpdatedTimeLabel的显示。
配置stateLabel和lastUpdatedTimeLabel
#pragma mark - 日历获取在9.x之后的系统使用currentCalendar会出异常。在8.0之后使用系统新API。(这里的适配,我们要学习,以后在项目中使用)
- (NSCalendar *)currentCalendar {
if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) {
return [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
}
return [NSCalendar currentCalendar];
}
#pragma mark key的处理
- (void)setLastUpdatedTimeKey:(NSString *)lastUpdatedTimeKey
{
[super setLastUpdatedTimeKey:lastUpdatedTimeKey];
// 如果label隐藏了,就不用再处理
if (self.lastUpdatedTimeLabel.hidden) return;
NSDate *lastUpdatedTime = [[NSUserDefaults standardUserDefaults] objectForKey:lastUpdatedTimeKey];
// 如果有block
if (self.lastUpdatedTimeText) {
self.lastUpdatedTimeLabel.text = self.lastUpdatedTimeText(lastUpdatedTime);
return;
}
if (lastUpdatedTime) {
// 1.获得年月日
NSCalendar *calendar = [self currentCalendar];
NSUInteger unitFlags = NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour |NSCalendarUnitMinute;
NSDateComponents *cmp1 = [calendar components:unitFlags fromDate:lastUpdatedTime];
NSDateComponents *cmp2 = [calendar components:unitFlags fromDate:[NSDate date]];
// 2.格式化日期
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
BOOL isToday = NO;
if ([cmp1 day] == [cmp2 day]) { // 今天
formatter.dateFormat = @" HH:mm";
isToday = YES;
} else if ([cmp1 year] == [cmp2 year]) { // 今年
formatter.dateFormat = @"MM-dd HH:mm";
} else {
formatter.dateFormat = @"yyyy-MM-dd HH:mm";
}
NSString *time = [formatter stringFromDate:lastUpdatedTime];
// 3.显示日期
self.lastUpdatedTimeLabel.text = [NSString stringWithFormat:@"%@%@%@",
[NSBundle mj_localizedStringForKey:MJRefreshHeaderLastTimeText],
isToday ? [NSBundle mj_localizedStringForKey:MJRefreshHeaderDateTodayText] : @"",
time];
} else {
self.lastUpdatedTimeLabel.text = [NSString stringWithFormat:@"%@%@",
[NSBundle mj_localizedStringForKey:MJRefreshHeaderLastTimeText],
[NSBundle mj_localizedStringForKey:MJRefreshHeaderNoneLastDateText]];
}
}
#pragma mark - 覆盖父类的方法
- (void)prepare
{
[super prepare];
// 初始化间距
self.labelLeftInset = MJRefreshLabelLeftInset;
// 初始化文字
[self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshHeaderIdleText] forState:MJRefreshStateIdle];
[self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshHeaderPullingText] forState:MJRefreshStatePulling];
[self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshHeaderRefreshingText] forState:MJRefreshStateRefreshing];
}
- (void)placeSubviews
{
[super placeSubviews];
if (self.stateLabel.hidden) return;
BOOL noConstrainsOnStatusLabel = self.stateLabel.constraints.count == 0;
if (self.lastUpdatedTimeLabel.hidden) {
// 状态
if (noConstrainsOnStatusLabel) self.stateLabel.frame = self.bounds;
} else {
CGFloat stateLabelH = self.mj_h * 0.5;
// 状态
if (noConstrainsOnStatusLabel) {
self.stateLabel.mj_x = 0;
self.stateLabel.mj_y = 0;
self.stateLabel.mj_w = self.mj_w;
self.stateLabel.mj_h = stateLabelH;
}
// 更新时间
if (self.lastUpdatedTimeLabel.constraints.count == 0) {
self.lastUpdatedTimeLabel.mj_x = 0;
self.lastUpdatedTimeLabel.mj_y = stateLabelH;
self.lastUpdatedTimeLabel.mj_w = self.mj_w;
self.lastUpdatedTimeLabel.mj_h = self.mj_h - self.lastUpdatedTimeLabel.mj_y;
}
}
}
- (void)setState:(MJRefreshState)state
{
MJRefreshCheckState
// 设置状态文字
self.stateLabel.text = self.stateTitles[@(state)];
// 重新设置key(重新显示时间),在这里触发setLastUpdatedTimeKey从而更新显示内容
self.lastUpdatedTimeKey = self.lastUpdatedTimeKey;
}
- (UILabel *)stateLabel
{
if (!_stateLabel) {
[self addSubview:_stateLabel = [UILabel mj_label]];
}
return _stateLabel;
}
- (UILabel *)lastUpdatedTimeLabel
{
if (!_lastUpdatedTimeLabel) {
[self addSubview:_lastUpdatedTimeLabel = [UILabel mj_label]];
}
return _lastUpdatedTimeLabel;
}
总结
MJRefreshStateHeader的部分其实不难,只是根据state更新两个label的文本。
1.依然还是在prepare做好初始数据的配置,两个label已经做好了懒加载,使用到的时候就会添加上视图。
2.然后在placeSubviews的时候做好视图的更新
3.依旧是在setState的时候更改文本内容
MJRefreshNormalHeader(继承MJRefreshStateHeader)
代码逻辑
MJRefreshNormalHeader是在MJRefreshStateHeader两个label的基础上,加上了arrowView和loadingView
从代码的角度,只是在MJRefreshStateHeader的基础上加上了两个UI控件而已,其他基本没有发生大的变化,在setState的时候设置loadingView和arrowView的显示
配置_arrowView和loadingView
#pragma mark - 重写父类的方法
- (void)prepare
{
[super prepare];
self.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
}
- (void)placeSubviews
{
[super placeSubviews];
// 箭头的中心点
CGFloat arrowCenterX = self.mj_w * 0.5;
if (!self.stateLabel.hidden) {
CGFloat stateWidth = self.stateLabel.mj_textWith;
CGFloat timeWidth = 0.0;
if (!self.lastUpdatedTimeLabel.hidden) {
timeWidth = self.lastUpdatedTimeLabel.mj_textWith;
}
CGFloat textWidth = MAX(stateWidth, timeWidth);
arrowCenterX -= textWidth / 2 + self.labelLeftInset;
}
CGFloat arrowCenterY = self.mj_h * 0.5;
CGPoint arrowCenter = CGPointMake(arrowCenterX, arrowCenterY);
// 箭头
if (self.arrowView.constraints.count == 0) {
self.arrowView.mj_size = self.arrowView.image.size;
self.arrowView.center = arrowCenter;
}
// 圈圈
if (self.loadingView.constraints.count == 0) {
self.loadingView.center = arrowCenter;
}
self.arrowView.tintColor = self.stateLabel.textColor;
}
- (void)setState:(MJRefreshState)state
{
MJRefreshCheckState
// 根据状态做事情
if (state == MJRefreshStateIdle) {
if (oldState == MJRefreshStateRefreshing) {
//从刷新中,转到常规状态,对于arrowView设置transform为初始值就可以了
self.arrowView.transform = CGAffineTransformIdentity;
//同时做透明度动画,隐藏菊花
[UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{
self.loadingView.alpha = 0.0;
} completion:^(BOOL finished) {
// 如果执行完动画发现不是idle状态,就直接返回,进入其他状态
if (self.state != MJRefreshStateIdle) return;
self.loadingView.alpha = 1.0;
[self.loadingView stopAnimating];
self.arrowView.hidden = NO;
}];
} else {
//即是说恢复成常规状态(只要不是在刷新的状态,那么菊花停止动画就可以了,同时让arrowView恢复到初始值就可以了)
[self.loadingView stopAnimating];
self.arrowView.hidden = NO;
[UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{
self.arrowView.transform = CGAffineTransformIdentity;
}];
}
} else if (state == MJRefreshStatePulling) {
//即是说恢复成正在拉取状态(菊花停止动画,同时让arrowView旋转180度就可以了)
[self.loadingView stopAnimating];
self.arrowView.hidden = NO;
[UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{
self.arrowView.transform = CGAffineTransformMakeRotation(0.000001 - M_PI);
}];
} else if (state == MJRefreshStateRefreshing) {
//即是说刷新状态(菊花开始动画,同时隐藏arrowView)
self.loadingView.alpha = 1.0; // 防止refreshing -> idle的动画完毕动作没有被执行
[self.loadingView startAnimating];
self.arrowView.hidden = YES;
}
}
#pragma mark - 懒加载子控件
- (UIImageView *)arrowView
{
if (!_arrowView) {
UIImageView *arrowView = [[UIImageView alloc] initWithImage:[NSBundle mj_arrowImage]];
[self addSubview:_arrowView = arrowView];
}
return _arrowView;
}
- (UIActivityIndicatorView *)loadingView
{
if (!_loadingView) {
UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:self.activityIndicatorViewStyle];
loadingView.hidesWhenStopped = YES;
[self addSubview:_loadingView = loadingView];
}
return _loadingView;
}
总结
MJRefreshNormalHeader和MJRefreshStateHeader基本一样,代码格式也差不多的,所以也是prepare设置初始数据,placeSubviews更新控件位置,setState更新菊花和arrowView的显示
MJRefreshGifHeader(继承MJRefreshStateHeader)
代码逻辑
MJRefreshGifHeader和MJRefreshNormalHeader的区别只是把菊花和arrowView换成了gifView,其他的代码逻辑基本一样
配置gifView
#pragma mark - 懒加载
- (UIImageView *)gifView
{
if (!_gifView) {
UIImageView *gifView = [[UIImageView alloc] init];
[self addSubview:_gifView = gifView];
}
return _gifView;
}
#pragma mark - 公共方法
- (void)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state
{
if (images == nil) return;
self.stateImages[@(state)] = images;
self.stateDurations[@(state)] = @(duration);
/* 根据图片设置控件的高度 */
UIImage *image = [images firstObject];
if (image.size.height > self.mj_h) {
//如果图片太大,就更新header的高度
self.mj_h = image.size.height;
}
}
- (void)setImages:(NSArray *)images forState:(MJRefreshState)state
{
[self setImages:images duration:images.count * 0.1 forState:state];
}
#pragma mark - 实现父类的方法
- (void)prepare
{
[super prepare];
// 初始化间距
self.labelLeftInset = 20;
}
- (void)setPullingPercent:(CGFloat)pullingPercent
{
[super setPullingPercent:pullingPercent];
NSArray *images = self.stateImages[@(MJRefreshStateIdle)];
if (self.state != MJRefreshStateIdle || images.count == 0) return;
// 停止动画
[self.gifView stopAnimating];
// 设置当前需要显示的图片
NSUInteger index = images.count * pullingPercent;
if (index >= images.count) index = images.count - 1;
self.gifView.image = images[index];
}
- (void)placeSubviews
{
[super placeSubviews];
if (self.gifView.constraints.count) return;
self.gifView.frame = self.bounds;
if (self.stateLabel.hidden && self.lastUpdatedTimeLabel.hidden) {
self.gifView.contentMode = UIViewContentModeCenter;
} else {
self.gifView.contentMode = UIViewContentModeRight;
CGFloat stateWidth = self.stateLabel.mj_textWith;
CGFloat timeWidth = 0.0;
if (!self.lastUpdatedTimeLabel.hidden) {
timeWidth = self.lastUpdatedTimeLabel.mj_textWith;
}
CGFloat textWidth = MAX(stateWidth, timeWidth);
self.gifView.mj_w = self.mj_w * 0.5 - textWidth * 0.5 - self.labelLeftInset;
}
}
- (void)setState:(MJRefreshState)state
{
MJRefreshCheckState
// 根据状态做事情
if (state == MJRefreshStatePulling || state == MJRefreshStateRefreshing) {
NSArray *images = self.stateImages[@(state)];
if (images.count == 0) return;
//重置播放,重新播放gif图片
[self.gifView stopAnimating];
if (images.count == 1) { // 单张图片
self.gifView.image = [images lastObject];
} else { // 多张图片
self.gifView.animationImages = images;
self.gifView.animationDuration = [self.stateDurations[@(state)] doubleValue];
[self.gifView startAnimating];
}
} else if (state == MJRefreshStateIdle) {
//原始状态的时候,隐藏动画
[self.gifView stopAnimating];
}
}
总结
MJRefreshGifHeader和MJRefreshNormalHeader差不多,比较新颖的就是使用了UIImageView的animationImages和animationDuration属性来实现gif动画的效果
MJRefreshAutoFooter(继承MJRefreshFooter)
代码逻辑
整体难度不大,核心就是通过监听contentOffset的改变,当达到底部的时候,自动调用beginRefreshing,更新State,然后在更新完成后,更新hidden从而修改UIScrollView的contentInset和footer的位置来实现加载完毕后隐藏尾部
配置footer的核心操作
#pragma mark - 实现父类的方法
- (void)prepare
{
[super prepare];
// 默认底部控件100%出现时才会自动刷新
self.triggerAutomaticallyRefreshPercent = 1.0;
// 设置为默认状态
self.automaticallyRefresh = YES;
}
- (void)scrollViewContentSizeDidChange:(NSDictionary *)change
{
[super scrollViewContentSizeDidChange:change];
// 设置位置,将尾部放在scrollView的底部,即contentSize的height处
self.mj_y = self.scrollView.mj_contentH;
}
- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change
{
[super scrollViewContentOffsetDidChange:change];
//也就是说当state不等于空闲状态,并且不是自动更新,并且scrollView没有生成的时候,都停止下面的判断自动更新的操作。(这个思路很好,不管后面会不会走到,但是逻辑上不应该走,就要杜绝)
if (self.state != MJRefreshStateIdle || !self.automaticallyRefresh || self.mj_y == 0) return;
// 内容超过一个屏幕
if (_scrollView.mj_insetT + _scrollView.mj_contentH > _scrollView.mj_h) {
// 这里的_scrollView.mj_contentH替换掉self.mj_y更为合理
if (_scrollView.mj_offsetY >= _scrollView.mj_contentH - _scrollView.mj_h + self.mj_h * self.triggerAutomaticallyRefreshPercent + _scrollView.mj_insetB - self.mj_h) {
// 防止手松开时连续调用
CGPoint old = [change[@"old"] CGPointValue];
CGPoint new = [change[@"new"] CGPointValue];
if (new.y <= old.y) return;
// 当底部刷新控件完全出现时,才刷新
[self beginRefreshing];
}
}
}
- (void)scrollViewPanStateDidChange:(NSDictionary *)change
{
[super scrollViewPanStateDidChange:change];
if (self.state != MJRefreshStateIdle) return;
// 手松开
if (_scrollView.panGestureRecognizer.state == UIGestureRecognizerStateEnded) {
//当手拉开的时候,两种情况,一种本身scrollView自身就没有屏幕高,而且你还在向上拉,那么触发自动加载更多,另一种就是scrollView比屏幕还高(大部分都是这样),并且你拉的区域比mj_contentH + 底部的contentInset的bottom - scrollView的frame的高,证明你当前已经拉到底部,那么当然也要加载更多。
// 不够一个屏幕
if (_scrollView.mj_insetT + _scrollView.mj_contentH <= _scrollView.mj_h) {
// 向上拽
if (_scrollView.mj_offsetY >= - _scrollView.mj_insetT) {
[self beginRefreshing];
}
} else { // 超出一个屏幕
if (_scrollView.mj_offsetY >= _scrollView.mj_contentH + _scrollView.mj_insetB - _scrollView.mj_h) {
[self beginRefreshing];
}
}
}
}
- (void)setState:(MJRefreshState)state
{
MJRefreshCheckState
if (state == MJRefreshStateRefreshing) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self executeRefreshingCallback];
});
} else if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) {
if (MJRefreshStateRefreshing == oldState) {
if (self.endRefreshingCompletionBlock) {
self.endRefreshingCompletionBlock();
}
}
}
}
- (void)setHidden:(BOOL)hidden
{
BOOL lastHidden = self.isHidden;
[super setHidden:hidden];
if (!lastHidden && hidden) {
self.state = MJRefreshStateIdle;
self.scrollView.mj_insetB -= self.mj_h;
} else if (lastHidden && !hidden) {
self.scrollView.mj_insetB += self.mj_h;
// 设置位置
self.mj_y = _scrollView.mj_contentH;
}
}
总结
MJRefreshAutoFooter的想法也是很好,通过监听contentOffset的变化,然后根据contentInset,scrollView自身的frame一起结合起来判断scrollView当前滚动的状态,从而来判断是否加载更多
MJRefreshBackFooter(继承MJRefreshFooter)
代码逻辑
整体难度不大,核心就是通过监听contentOffset的改变,当达到底部的时候,自动调用beginRefreshing,更新State,然后在更新完成后,修改UIScrollView的contentInset和footer的位置来实现加载完毕后出现回弹效果
配置footer核心操作
#pragma mark - 实现父类的方法
- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change
{
[super scrollViewContentOffsetDidChange:change];
// 如果正在刷新,直接返回
if (self.state == MJRefreshStateRefreshing) return;
_scrollViewOriginalInset = self.scrollView.contentInset;
// 当前的contentOffset
CGFloat currentOffsetY = self.scrollView.mj_offsetY;
// 尾部控件刚好出现的offsetY
CGFloat happenOffsetY = [self happenOffsetY];
// 如果是向下滚动到看不见尾部控件,直接返回
if (currentOffsetY <= happenOffsetY) return;
CGFloat pullingPercent = (currentOffsetY - happenOffsetY) / self.mj_h;
// 如果已全部加载,仅设置pullingPercent,然后返回
if (self.state == MJRefreshStateNoMoreData) {
self.pullingPercent = pullingPercent;
return;
}
if (self.scrollView.isDragging) {
self.pullingPercent = pullingPercent;
// 普通 和 即将刷新 的临界点
CGFloat normal2pullingOffsetY = happenOffsetY + self.mj_h;
if (self.state == MJRefreshStateIdle && currentOffsetY > normal2pullingOffsetY) {
// 转为即将刷新状态
self.state = MJRefreshStatePulling;
} else if (self.state == MJRefreshStatePulling && currentOffsetY <= normal2pullingOffsetY) {
// 转为普通状态
self.state = MJRefreshStateIdle;
}
} else if (self.state == MJRefreshStatePulling) {// 即将刷新 && 手松开
// 开始刷新
[self beginRefreshing];
} else if (pullingPercent < 1) {
self.pullingPercent = pullingPercent;
}
}
- (void)scrollViewContentSizeDidChange:(NSDictionary *)change
{
[super scrollViewContentSizeDidChange:change];
// 内容的高度
CGFloat contentHeight = self.scrollView.mj_contentH + self.ignoredScrollViewContentInsetBottom;
// 表格的高度
CGFloat scrollHeight = self.scrollView.mj_h - self.scrollViewOriginalInset.top - self.scrollViewOriginalInset.bottom + self.ignoredScrollViewContentInsetBottom;
// 设置位置和尺寸
self.mj_y = MAX(contentHeight, scrollHeight);
}
- (void)setState:(MJRefreshState)state
{
MJRefreshCheckState
// 根据状态来设置属性
if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) {
// 刷新完毕
if (MJRefreshStateRefreshing == oldState) {
[UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{
self.scrollView.mj_insetB -= self.lastBottomDelta;
// 自动调整透明度
if (self.isAutomaticallyChangeAlpha) self.alpha = 0.0;
} completion:^(BOOL finished) {
self.pullingPercent = 0.0;
if (self.endRefreshingCompletionBlock) {
self.endRefreshingCompletionBlock();
}
}];
}
CGFloat deltaH = [self heightForContentBreakView];
// 刚刷新完毕
if (MJRefreshStateRefreshing == oldState && deltaH > 0 && self.scrollView.mj_totalDataCount != self.lastRefreshCount) {
self.scrollView.mj_offsetY = self.scrollView.mj_offsetY;
}
} else if (state == MJRefreshStateRefreshing) {
// 记录刷新前的数量
self.lastRefreshCount = self.scrollView.mj_totalDataCount;
[UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{
CGFloat bottom = self.mj_h + self.scrollViewOriginalInset.bottom;
CGFloat deltaH = [self heightForContentBreakView];
if (deltaH < 0) { // 如果内容高度小于view的高度
bottom -= deltaH;
}
self.lastBottomDelta = bottom - self.scrollView.mj_insetB;
self.scrollView.mj_insetB = bottom;
self.scrollView.mj_offsetY = [self happenOffsetY] + self.mj_h;
} completion:^(BOOL finished) {
[self executeRefreshingCallback];
}];
}
}
- (void)endRefreshing
{
dispatch_async(dispatch_get_main_queue(), ^{
self.state = MJRefreshStateIdle;
});
}
- (void)endRefreshingWithNoMoreData
{
dispatch_async(dispatch_get_main_queue(), ^{
self.state = MJRefreshStateNoMoreData;
});
}
总结
MJRefreshBackFooter的想法也是很好,通过监听contentOffset的变化,然后根据contentInset,scrollView自身的frame一起结合起来判断scrollView当前滚动的状态,从而来判断是否加载更多,并且在加载完成后,更新UI视图,从而实现收起来的视觉效果