iOS-MJRefresh框架底層實(shí)現(xiàn)原理

這兩天研究了一下MJRefresh框架底層實(shí)現(xiàn)原理,下面貼出研究結(jié)果:


#import "ViewController.h"
#import "MJExtension.h"
#import "AFNetworking.h"
#import "UIView+Frame.h"
#import "TopicItem.h"

@interface ViewController ()

//* 請(qǐng)求管理者 
@property (nonatomic, weak) AFHTTPSessionManager *mgr;
/** 全部的帖子數(shù)據(jù) */
@property (nonatomic, strong) NSMutableArray *topics;
/** 用來(lái)加載下一頁(yè)數(shù)據(jù) */
@property (nonatomic, copy) NSString *maxtime;

/******** 下拉刷新-header ********/
/** 下拉刷新控件 */
@property (nonatomic, weak) UIView *header;
/** 下拉刷新控件里面的文字 */
@property (nonatomic, weak) UILabel *headerLabel;
/** 是否為"松開(kāi)立即刷新" */
@property(nonatomic, assign, getter=isWillLoadingNewData) BOOL willLoadingNewData;
/** 是否為"正在刷新" */
@property(nonatomic, assign, getter=isLoadingNewData) BOOL loadingNewData;
/******** 下拉刷新-header ********/

/******** 上拉刷新-footer ********/
/** 上拉刷新控件 */
@property (nonatomic, weak) UIView *footer;
/** 上拉刷新控件里面的文字 */
@property (nonatomic, weak) UILabel *footerLabel;
/** 是否正在加載更多數(shù)據(jù) */
@property(nonatomic, assign, getter=isLoadingMoreData) BOOL loadingMoreData;
/******** 上拉刷新-footer ********/

@end

@implementation ViewController

#pragma mark - 懶加載
- (AFHTTPSessionManager *)mgr
{
    if (!_mgr) {
        _mgr = [AFHTTPSessionManager manager];
    }
    return _mgr;
}

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.contentInset = UIEdgeInsetsMake(61, 0, 0, 0);
    
    // 集成刷新控件
    [self setUpRefresh];
    
    [self loadNewTopics];
}

/**
 * 集成刷新控件
 */
- (void)setUpRefresh
{
    // 下拉刷新:加載最新的數(shù)據(jù)
    UIView *header = [[UIView alloc] init];
    header.backgroundColor = [UIColor yellowColor];
    header.height = 60;
    header.width = self.tableView.width;
    header.y = - header.height;
    [self.tableView addSubview:header];
    self.header = header;
    
    UILabel *headerLabel = [[UILabel alloc] init];
    headerLabel.text = @"下拉可以刷新";
    headerLabel.width = self.tableView.width;
    headerLabel.height = header.height;
    headerLabel.textAlignment = NSTextAlignmentCenter;
    [header addSubview:headerLabel];
    self.headerLabel = headerLabel;
    
    // 上拉刷新:加載更多的數(shù)據(jù)
    UIView *footer = [[UIView alloc] init];
    footer.backgroundColor = [UIColor orangeColor];
    footer.height = 35;
    footer.hidden = YES;
    self.tableView.tableFooterView = footer;
    self.footer = footer;
    
    UILabel *footerLabel = [[UILabel alloc] init];
    footerLabel.text = @"上拉可以加載更多";
    footerLabel.width = self.tableView.width;
    footerLabel.height = footer.height;
    footerLabel.textAlignment = NSTextAlignmentCenter;
    [footer addSubview:footerLabel];
    self.footerLabel = footerLabel;
}

#pragma mark - 數(shù)據(jù)處理
/**
 * 加載最新的帖子數(shù)據(jù)
 */
- (void)loadNewTopics
{
    // 拼接請(qǐng)求參數(shù)
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"list";
    parameters[@"c"] = @"data";
    parameters[@"type"] = @"1";
    
    // 發(fā)送請(qǐng)求
    [self.mgr GET:@"http://api.budejie.com/api/api_open.php" parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 存儲(chǔ)maxtime
        self.maxtime = responseObject[@"info"][@"maxtime"];
        
        // 字典數(shù)組 -> 模型數(shù)組
        self.topics = [TopicItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        // 刷新表格
        [self.tableView reloadData];
        
        // 結(jié)束刷新
        self.loadingNewData = NO;
        // 恢復(fù)頂部的內(nèi)邊距
        [UIView animateWithDuration:0.25 animations:^{
            UIEdgeInsets inset = self.tableView.contentInset;
            inset.top -= self.header.height;
            self.tableView.contentInset = inset;
        }];
        
        // 有數(shù)據(jù)了
        self.footer.hidden = NO;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"請(qǐng)求失敗 - %@", error);
        // 結(jié)束刷新
        self.loadingNewData = NO;
        // 恢復(fù)頂部的內(nèi)邊距
        [UIView animateWithDuration:0.25 animations:^{
            UIEdgeInsets inset = self.tableView.contentInset;
            inset.top -= self.header.height;
            self.tableView.contentInset = inset;
        }];
    }];
}

/**
 * 加載更多的帖子數(shù)據(jù)
 */
- (void)loadMoreTopics
{
    // 拼接請(qǐng)求參數(shù)
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"list";
    parameters[@"c"] = @"data";
    parameters[@"type"] = @"1";
    parameters[@"maxtime"] = self.maxtime;
    
    // 發(fā)送請(qǐng)求
    [self.mgr GET:@"http://api.budejie.com/api/api_open.php" parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 存儲(chǔ)maxtime
        self.maxtime = responseObject[@"info"][@"maxtime"];
        
        // 字典數(shù)組 -> 模型數(shù)組
        NSArray *moreTopics = [TopicItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [self.topics addObjectsFromArray:moreTopics];
        
        // 刷新表格
        [self.tableView reloadData];
        
        // 結(jié)束刷新
        self.loadingMoreData = NO;
        self.footerLabel.text = @"上拉可以加載更多";
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"請(qǐng)求失敗 - %@", error);
        
        // 結(jié)束刷新
        self.loadingMoreData = NO;
        self.footerLabel.text = @"上拉可以加載更多";
    }];
}

#pragma mark - 代理方法
/**
 * 當(dāng)scrollView在滾動(dòng),就會(huì)調(diào)用這個(gè)代理方法
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 處理下拉刷新
    [self dealLoadNewData];
    
    // 處理上拉加載更多
    [self dealLoadMoreData];
}

/**
 * 當(dāng)用戶手松開(kāi)(停止拖拽),就會(huì)調(diào)用這個(gè)代理方法
 */
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.willLoadingNewData == NO || self.loadingNewData) return;
    
    // 增加頂部的內(nèi)邊距
    [UIView animateWithDuration:0.25 animations:^{
        UIEdgeInsets inset = self.tableView.contentInset;
        inset.top += self.header.height;
        self.tableView.contentInset = inset;
    }];
    
    // 修改文字
    self.headerLabel.text = @"正在刷新數(shù)據(jù)...";
    
    // 正在刷新
    self.loadingNewData = YES;
    
    // 發(fā)送請(qǐng)求
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self loadNewTopics];
    });
}

/**
 * 處理下拉刷新
 */
- (void)dealLoadNewData
{
    if (self.loadingNewData) return;
    
    CGFloat offsetY =  - (64 + self.header.height);
    if (self.tableView.contentOffset.y <= offsetY) {
        self.headerLabel.text = @"松開(kāi)立即刷新";
        self.willLoadingNewData = YES;
    } else {
        self.headerLabel.text = @"下拉可以刷新";
        self.willLoadingNewData = NO;
    }
}

/**
 * 處理上拉加載更多
 */
- (void)dealLoadMoreData
{
    // 如果沒(méi)有數(shù)據(jù) 或者 正在上拉刷新, 直接返回
    if (self.topics.count == 0 || self.loadingMoreData) return;
    
    CGFloat offsetY = self.tableView.contentSize.height + self.tableView.contentInset.bottom - self.tableView.height;
    if (self.tableView.contentOffset.y >= offsetY) {
        self.loadingMoreData = YES;
        
        // 更改文字
        self.footerLabel.text = @"正在加載更多的數(shù)據(jù)...";
        
        // 加載更多的帖子數(shù)據(jù)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self loadMoreTopics];
        });
    }
}

#pragma mark - 數(shù)據(jù)源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.topics.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    
    TopicItem *item = self.topics[indexPath.row];
    cell.textLabel.text = item.name;
    cell.detailTextLabel.text = item.text;
    
    return cell;
}
@end
效果
實(shí)現(xiàn)原理

在tableView上加上一個(gè)View,注意不是headerView,而是一個(gè)Y值為負(fù)數(shù)的普通View,下拉時(shí)候監(jiān)聽(tīng)偏移量,改變View的內(nèi)容顯示。
在tableView下面加上一個(gè)footerView,監(jiān)聽(tīng)偏移量,當(dāng)footerView完全顯示的時(shí)候加載更多數(shù)據(jù)。
基本代碼已貼,有不清楚的可以討論交流。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 實(shí)現(xiàn)原理在tableView上加上一個(gè)View,注意不是headerView,而是一個(gè)Y值為負(fù)數(shù)的普通View,下...
    ScaryMonsterLyn閱讀 792評(píng)論 0 2
  • 有時(shí)候我們需要編寫(xiě)一些小的代碼片段時(shí),在Visual Studio中創(chuàng)建一個(gè)工程就顯得有點(diǎn)殺雞用牛刀的感覺(jué)了,所有...
    簡(jiǎn)約生活_憶沙閱讀 2,153評(píng)論 0 0
  • 它本來(lái)是只活得很矜持的豬,坐在一個(gè)女孩的窗臺(tái)上,拱著手晚上數(shù)著星星白天暖暖地曬肚皮。雖然它什么都不說(shuō),但它就是知道...
    慣犯2閱讀 960評(píng)論 0 0
  • 記憶中很長(zhǎng)一段時(shí)間都沒(méi)有休息過(guò)這么久的假,長(zhǎng)假還是停留在學(xué)生時(shí)代的暑假和寒假,工作了三年突然讓我停下來(lái)休息,...
    遇見(jiàn)未知的自己珍珍閱讀 489評(píng)論 2 1
  • 凜冽的北風(fēng)吹著哨子掠過(guò)大地,公路兩旁灰色的楊樹(shù)林也瑟瑟發(fā)抖,夕陽(yáng)也擔(dān)心著涼似的,慌慌張張地躲到地平線下去?;氐阶约?..
    刀客181閱讀 428評(píng)論 0 0

友情鏈接更多精彩內(nèi)容