MJRefresh七MJRefreshRighter

MJRefreshRighter

由于產(chǎn)品設計了一個可橫向滾動狱窘,在滾動末還要顯示加載更多的設計,看了MJRefresh沒有支持這種格式的财搁,昨天研究一番MJRefresh的源碼后依葫蘆畫瓢的寫了一個支持水平滑動加載更多的刷新組件,組件依賴于MJRefresh


MJRefreshRighter.h

@interface MJRefreshRighter : MJRefreshComponent
/** 忽略多少scrollView的contentInset的right */
@property (assign, nonatomic) CGFloat ignoredScrollViewContentInsetRight;
+ (instancetype)righterWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock;
/** 創(chuàng)建righter */
+ (instancetype)righterWithRefreshingTarget:(id)target refreshingAction:(SEL)action;
/** 提示沒有更多的數(shù)據(jù) */
- (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) {
        // 監(jiān)聽scrollView數(shù)據(jù)的變化
        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 - 實現(xiàn)父類的方法
- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change
{
    [super scrollViewContentOffsetDidChange:change];
    // 如果正在刷新躬络,直接返回
    if (self.state == MJRefreshStateRefreshing) return;
    _scrollViewOriginalInset = self.scrollView.contentInset;
    
    // 當前的contentOffset
    CGFloat currentOffsetX = self.scrollView.mj_offsetX;
    // 尾部控件剛好出現(xiàn)的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) {
            // 轉(zhuǎn)為即將刷新狀態(tài)
            self.state = MJRefreshStatePulling;
        } else if (self.state == MJRefreshStatePulling && currentOffsetX <= normal2pullingOffsetX) {
            // 轉(zhuǎn)為普通狀態(tài)
            self.state = MJRefreshStateIdle;
        }
    }else if (self.state == MJRefreshStatePulling) {// 即將刷新 && 手松開
        // 開始刷新
        [self beginRefreshing];
    } else if (pullingPercent < 1) {
        self.pullingPercent = pullingPercent;
    }
}
- (void)scrollViewContentSizeDidChange:(NSDictionary *)change
{
    [super scrollViewContentSizeDidChange:change];
    
    // 內(nèi)容的寬度度
    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
    
    // 根據(jù)狀態(tài)來設置屬性
    if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) {
        // 刷新完畢
        if (MJRefreshStateRefreshing == oldState) {
            
            [UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{
                self.scrollView.mj_insetR -= self.lastRightDelta;
                
                // 自動調(diào)整透明度
                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;
        
        // 記錄刷新前的數(shù)量
        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) { // 如果內(nèi)容寬度小于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) {
        // 記錄刷新前的數(shù)量
        
        [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的內(nèi)容 超出 view 的寬度
- (CGFloat)widthForContentBreakView
{
    // 一屏內(nèi)可真實顯示內(nèi)容的寬度茴扁,也就是減去前后的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
{
    // 算出從初始化時要滾動多久才能看見刷新控件
    // 全部內(nèi)容區(qū)域-顯示屏區(qū)域
    CGFloat deltaW = [self widthForContentBreakView];
    // 顯示內(nèi)容超過一屏
    if (deltaW > 0) {
        return deltaW - self.scrollViewOriginalInset.left;
    } else {
        // 顯示內(nèi)容不足一屏
        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

總結(jié):通過對你中狀態(tài)的修改進行不同的顯示
UIScrollView.contentinSet汪疮、contentOffset以及對各個距離長度的計算和以狀態(tài)變化為數(shù)據(jù)流管理

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末峭火,一起剝皮案震驚了整個濱河市毁习,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌卖丸,老刑警劉巖纺且,帶你破解...
    沈念sama閱讀 212,884評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異稍浆,居然都是意外死亡载碌,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,755評論 3 385
  • 文/潘曉璐 我一進店門衅枫,熙熙樓的掌柜王于貴愁眉苦臉地迎上來嫁艇,“玉大人,你說我怎么就攤上這事弦撩〔竭洌” “怎么了?”我有些...
    開封第一講書人閱讀 158,369評論 0 348
  • 文/不壞的土叔 我叫張陵孤钦,是天一觀的道長歧斟。 經(jīng)常有香客問我,道長偏形,這世上最難降的妖魔是什么静袖? 我笑而不...
    開封第一講書人閱讀 56,799評論 1 285
  • 正文 為了忘掉前任,我火速辦了婚禮俊扭,結(jié)果婚禮上队橙,老公的妹妹穿的比我還像新娘。我一直安慰自己萨惑,他們只是感情好捐康,可當我...
    茶點故事閱讀 65,910評論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著庸蔼,像睡著了一般解总。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上姐仅,一...
    開封第一講書人閱讀 50,096評論 1 291
  • 那天花枫,我揣著相機與錄音,去河邊找鬼掏膏。 笑死劳翰,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的馒疹。 我是一名探鬼主播佳簸,決...
    沈念sama閱讀 39,159評論 3 411
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼颖变!你這毒婦竟也來了生均?” 一聲冷哼從身側(cè)響起听想,我...
    開封第一講書人閱讀 37,917評論 0 268
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎疯特,沒想到半個月后哗魂,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,360評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡漓雅,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,673評論 2 327
  • 正文 我和宋清朗相戀三年录别,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片邻吞。...
    茶點故事閱讀 38,814評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡组题,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出抱冷,到底是詐尸還是另有隱情崔列,我是刑警寧澤,帶...
    沈念sama閱讀 34,509評論 4 334
  • 正文 年R本政府宣布旺遮,位于F島的核電站赵讯,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏耿眉。R本人自食惡果不足惜边翼,卻給世界環(huán)境...
    茶點故事閱讀 40,156評論 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望鸣剪。 院中可真熱鬧组底,春花似錦、人聲如沸筐骇。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,882評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽铛纬。三九已至厌均,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間告唆,已是汗流浹背莫秆。 一陣腳步聲響...
    開封第一講書人閱讀 32,123評論 1 267
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留悔详,地道東北人。 一個月前我還...
    沈念sama閱讀 46,641評論 2 362
  • 正文 我出身青樓惹挟,卻偏偏與公主長得像茄螃,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子连锯,可洞房花燭夜當晚...
    茶點故事閱讀 43,728評論 2 351

推薦閱讀更多精彩內(nèi)容