MJRefresh七MJRefreshRighter

MJRefreshRighter

由于产品设计了一个可横向滚动,在滚动末还要显示加载更多的设计,看了MJRefresh没有支持这种格式的,昨天研究一番MJRefresh的源码后依葫芦画瓢的写了一个支持水平滑动加载更多的刷新组件,组件依赖于MJRefresh


MJRefreshRighter.h

@interface MJRefreshRighter : MJRefreshComponent
/** 忽略多少scrollView的contentInset的right */
@property (assign, nonatomic) CGFloat ignoredScrollViewContentInsetRight;
+ (instancetype)righterWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock;
/** 创建righter */
+ (instancetype)righterWithRefreshingTarget:(id)target refreshingAction:(SEL)action;
/** 提示没有更多的数据 */
- (void)endRefreshingWithNoMoreData;
@end

MJRefreshRighter.m

#import "MJRefreshRighter.h"
@interface MJRefreshRighter()
@property (assign, nonatomic) NSInteger lastRefreshCount;
@property (assign, nonatomic) CGFloat lastRightDelta;
@property (nonatomic,strong) UILabel *statelbl;
@property (nonatomic,strong) UIImageView *arrowImageView;
@property (nonatomic,strong) UIActivityIndicatorView * indicator;
@property (nonatomic,strong) NSMutableDictionary * stateLblTextDictM;
@end
@implementation MJRefreshRighter
#pragma mark - 构造方法
+ (instancetype)righterWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock
{
    MJRefreshRighter *cmp = [[self alloc] init];
    cmp.refreshingBlock = refreshingBlock;
    return cmp;
}
+ (instancetype)righterWithRefreshingTarget:(id)target refreshingAction:(SEL)action
{
    MJRefreshRighter *cmp = [[self alloc] init];
    [cmp setRefreshingTarget:target refreshingAction:action];
    return cmp;
}
#pragma mark - 初始化
- (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) {
                self.hidden = (totalDataCount == 0);
            }];
        }
    }
   
    [self addSubview:self.statelbl];
    // 设置文字
    [self updateStateAttrTextWithState:self.state];
    [self addSubview:self.arrowImageView];
    [self addSubview:self.indicator];
   
    
    self.scrollView.alwaysBounceVertical = NO;
    self.scrollView.alwaysBounceHorizontal = YES;
    [self scrollViewContentSizeDidChange:nil];
}
#pragma mark - 实现父类的方法
- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change
{
    [super scrollViewContentOffsetDidChange:change];
    // 如果正在刷新,直接返回
    if (self.state == MJRefreshStateRefreshing) return;
    _scrollViewOriginalInset = self.scrollView.contentInset;
    
    // 当前的contentOffset
    CGFloat currentOffsetX = self.scrollView.mj_offsetX;
    // 尾部控件刚好出现的offsetX
    CGFloat happenOffsetX = [self happenOffsetX];
    // 如果是向右滚动到看不见尾部控件,直接返回
    if (currentOffsetX <= happenOffsetX) return;
    
    CGFloat pullingPercent = (currentOffsetX - happenOffsetX) / self.mj_w;
    // 如果已全部加载,仅设置pullingPercent,然后返回
    if (self.state == MJRefreshStateNoMoreData) {
        self.pullingPercent = pullingPercent;
        return;
    }
    CGFloat normal2pullingOffsetX = happenOffsetX + self.mj_w;
    if (self.scrollView.isDragging) { // 拖拽过程中的处理
        self.pullingPercent = pullingPercent;
        // 普通 和 即将刷新 的临界点,临界点位happenOffsetX刚好可见,happenOffsetX + self.mj_w全部可见,当全部可见时就为临界点
        
        
        // 超过临界点
        if (self.state == MJRefreshStateIdle && currentOffsetX > normal2pullingOffsetX) {
            // 转为即将刷新状态
            self.state = MJRefreshStatePulling;
        } else if (self.state == MJRefreshStatePulling && currentOffsetX <= normal2pullingOffsetX) {
            // 转为普通状态
            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 contentWidth = self.scrollView.mj_contentW + self.ignoredScrollViewContentInsetRight;
    // 表格的高度
    CGFloat scrollWidth = self.scrollView.mj_w - self.scrollViewOriginalInset.left - self.scrollViewOriginalInset.right + self.ignoredScrollViewContentInsetRight;
    // 设置位置和尺寸
    self.mj_x = MAX(contentWidth, scrollWidth);
    self.mj_y = 0;
    self.mj_h = self.scrollView.mj_h;
    
    
    self.arrowImageView.mj_x = 0;
    self.arrowImageView.mj_y = (self.mj_h-self.arrowImageView.image.size.height)/2.0;
    
    self.statelbl.mj_x = self.arrowImageView.mj_w+5;
    self.statelbl.mj_h = self.mj_h;
    self.statelbl.mj_w = 20;
    self.indicator.frame = self.arrowImageView.frame;
    
    self.mj_w = self.arrowImageView.mj_w+5+self.statelbl.mj_w+5;
    
    
}
- (void)setState:(MJRefreshState)state
{
    MJRefreshCheckState
    
    // 根据状态来设置属性
    if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) {
        // 刷新完毕
        if (MJRefreshStateRefreshing == oldState) {
            
            [UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{
                self.scrollView.mj_insetR -= self.lastRightDelta;
                
                // 自动调整透明度
                if (self.isAutomaticallyChangeAlpha) self.alpha = 0.0;
            } completion:^(BOOL finished) {
                self.pullingPercent = 0.0;
                
                if (self.endRefreshingCompletionBlock) {
                    self.endRefreshingCompletionBlock();
                }
            }];
            
        }
        self.indicator.hidden = YES;
        [self.indicator stopAnimating];
        self.arrowImageView.hidden = NO;
        if (state == MJRefreshStateNoMoreData) {
            self.arrowImageView.hidden = YES;
        }else{
            self.arrowImageView.hidden = NO;
        }
        [self updateStateAttrTextWithState:state];
        
        if (oldState == MJRefreshStateRefreshing) {
            self.arrowImageView.transform = CGAffineTransformMakeRotation(0.000001 - M_PI);
        }else{
            [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{
                self.arrowImageView.transform = CGAffineTransformMakeRotation(0.000001 - M_PI);
            }];
        }
        
        CGFloat deltaW = [self widthForContentBreakView];
        // 刚刷新完毕
        if (MJRefreshStateRefreshing == oldState && deltaW > 0 && self.scrollView.mj_totalDataCount != self.lastRefreshCount) {
            self.scrollView.mj_offsetX = self.scrollView.mj_offsetX;
            
        }
    } else if (state == MJRefreshStateRefreshing) {
        
        [self updateStateAttrTextWithState:state];
        self.indicator.hidden = NO;
        [self.indicator startAnimating];
        self.arrowImageView.hidden = YES;
        
        // 记录刷新前的数量
        self.lastRefreshCount = self.scrollView.mj_totalDataCount;
        // MJRefreshFastAnimationDuration
        [UIView animateWithDuration:0.1 animations:^{
            CGFloat right = self.mj_w + self.scrollViewOriginalInset.right;
            CGFloat deltaW = [self widthForContentBreakView];
            if (deltaW < 0) { // 如果内容宽度小于view的宽度
                right -= deltaW;
            }
            
            self.lastRightDelta = right - self.scrollView.mj_insetR;
            self.scrollView.mj_insetR = right;
            self.scrollView.mj_offsetX = [self happenOffsetX] + self.mj_w;
        } completion:^(BOOL finished) {
            [self executeRefreshingCallback];
        }];
        
    }else if (state == MJRefreshStatePulling) {
        // 记录刷新前的数量
        
        [self updateStateAttrTextWithState:state];
        self.indicator.hidden = YES;
        [self.indicator stopAnimating];
        self.arrowImageView.hidden = NO;
        
        [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{
            self.arrowImageView.transform = CGAffineTransformIdentity;
        }];
    }
}
- (void)endRefreshing
{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.state = MJRefreshStateIdle;
    });
}

- (void)endRefreshingWithNoMoreData
{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.state = MJRefreshStateNoMoreData;
    });
}
#pragma mark - 私有方法
#pragma mark 获得scrollView的内容 超出 view 的宽度
- (CGFloat)widthForContentBreakView
{
    // 一屏内可真实显示内容的宽度,也就是减去前后的padding
    CGFloat w = self.scrollView.frame.size.width - self.scrollViewOriginalInset.left - self.scrollViewOriginalInset.right;
    return self.scrollView.contentSize.width - w;
}
#pragma mark 刚好看到上拉刷新控件时的contentOffset.x
- (CGFloat)happenOffsetX
{
    // 算出从初始化时要滚动多久才能看见刷新控件
    // 全部内容区域-显示屏区域
    CGFloat deltaW = [self widthForContentBreakView];
    // 显示内容超过一屏
    if (deltaW > 0) {
        return deltaW - self.scrollViewOriginalInset.left;
    } else {
        // 显示内容不足一屏
        return - self.scrollViewOriginalInset.left;
    }
}
#pragma mark - getter & setter
- (UILabel *)statelbl
{
    if (_statelbl == nil) {
        
        _statelbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 40)];
        _statelbl.font = [UIFont systemFontOfSize:10];
        _statelbl.textAlignment = NSTextAlignmentCenter;
        _statelbl.numberOfLines = 0;
    }
    return _statelbl;
}
- (void)updateStateAttrTextWithState:(MJRefreshState)state
{
    NSString *text = self.stateLblTextDictM[@(state)];
    NSRange range = NSRangeFromString(text);
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text];
    [attr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:range];
    [attr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"929292"] range:range];
    [LYUtil addLineSpaceWithMutableAttbuteString:attr lineSpace:3];

    self.statelbl.attributedText = attr;
}
- (UIImageView *)arrowImageView
{
    if (_arrowImageView == nil) {
            _arrowImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"back_circle_arrow"]];
    }
    return _arrowImageView;
}
- (UIActivityIndicatorView *)indicator
{
    if (_indicator == nil) {
        _indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _indicator.hidden = YES;
        [_indicator stopAnimating];
    }
    return _indicator;
}
- (NSMutableDictionary *)stateLblTextDictM
{
    if (_stateLblTextDictM == nil) {
        _stateLblTextDictM = [NSMutableDictionary dictionary];
        _stateLblTextDictM[@(MJRefreshStateIdle)] = @"左滑加载更多";
         _stateLblTextDictM[@(MJRefreshStatePulling)] = @"释放加载更多";
        _stateLblTextDictM[@(MJRefreshStateRefreshing)] = @"正在加载";
        _stateLblTextDictM[@(MJRefreshStateWillRefresh)] = @"即将加载更多";
        _stateLblTextDictM[@(MJRefreshStateNoMoreData)] = @"全部加载完毕";

    }
    return _stateLblTextDictM;
}
@end

用分类的方式让UIScrollView有righter
UIScrollView+ZQQMJRefresh.h

#import <UIKit/UIKit.h>
#import "MJRefreshConst.h"
#import "MJRefreshRighter.h"

@interface UIScrollView (ZQQMJRefresh)
/** 右拉刷新控件 */
@property (strong, nonatomic) MJRefreshRighter *mj_righter;
@end

UIScrollView+ZQQMJRefresh.m

#import "UIScrollView+ZQQMJRefresh.h"

@implementation UIScrollView (ZQQMJRefresh)
#pragma mark - righter
static const char LYMJRefreshRighterKey = '\0';
- (void)setMj_righter:(MJRefreshRighter *)mj_righter
{
    if (mj_righter != self.mj_righter) {
        // 删除旧的,添加新的
        [self.mj_righter removeFromSuperview];
        [self insertSubview:mj_righter atIndex:0];
        
        // 存储新的
        [self willChangeValueForKey:@"mj_righter"]; // KVO
        objc_setAssociatedObject(self, &LYMJRefreshRighterKey, mj_righter, OBJC_ASSOCIATION_ASSIGN);
        [self didChangeValueForKey:@"mj_righter"];
    }
}
- (MJRefreshRighter *)mj_righter
{
    return objc_getAssociatedObject(self, &LYMJRefreshRighterKey);
}
@end

总结:通过对你中状态的修改进行不同的显示
UIScrollView.contentinSet、contentOffset以及对各个距离长度的计算和以状态变化为数据流管理

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,417评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,921评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,850评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,945评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,069评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,188评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,239评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,994评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,409评论 1 304
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,735评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,898评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,578评论 4 336
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,205评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,916评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,156评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,722评论 2 363
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,781评论 2 351

推荐阅读更多精彩内容