iOS-MJ刷新小结(下拉+上拉)

1.MJRefresh基本介绍

使用MJRefresh进行刷新操作,根据需求进行是否分页,从而进行下拉刷新和上拉加载更多;MJRefresh的github地址:https://github.com/CoderMJLee/MJRefresh

相关链接:
下拉刷新和上拉加载之MJRefresh篇:https://www.jianshu.com/p/9b7b86d23a63

  • 刷新控件的状态:
typedef NS_ENUM(NSInteger, MJRefreshState) {// 刷新控件的状态
    
    MJRefreshStateIdle = 1,// 普通闲置状态
    MJRefreshStatePulling,// 松开就可以进行刷新的状态
    MJRefreshStateRefreshing,// 正在刷新中的状态
    MJRefreshStateWillRefresh,// 即将刷新的状态
    MJRefreshStateNoMoreData// 所有数据加载完毕,没有更多的数据了
};

2.演示Demo如下:

效果图:

下拉-MJRefreshStateIdle

下拉-MJRefreshStatePulling
下拉-MJRefreshStateRefreshing
上拉-MJRefreshStateIdle
上拉-MJRefreshStateRefreshing
上拉-MJRefreshStateNoMoreData

后台返回数据的结构:

后台返回数据的结构

代码:

#import "UToPeopleManagerViewController.h"
#import "UToPeopleManagerCell.h"
#import "UToNavView.h"

@interface UToPeopleManagerViewController () {
    
    int pageNum;// 页数(第几页)
    int pageSize;// 每页加载最多的数量
    MJRefreshNormalHeader *header;
    MJRefreshAutoNormalFooter *footer;
}

@property (nonatomic, strong) UToTableView *setTableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UToNavView *navView;// 导航栏

@end
@implementation UToPeopleManagerViewController

// 网络请求成功
- (void)SXBaseNetWork:(SXBaseNetWork *)network complete:(id)responseObject identifier:(NSString *)identifier {
    
    if (self.setTableView.mj_header.isRefreshing) {
        
        [self.setTableView.mj_header endRefreshing];
    }
    if (self.setTableView.mj_footer.isRefreshing) {
        
        [self.setTableView.mj_footer endRefreshing];
    }
    [self.hud hideAnimated:YES];
    int code = [responseObject[@"code"] intValue];
    
    WEAKSELF
    
    if (code !=200) {
        
        NSString * msg = responseObject[@"message"];
        [weakSelf showHudMsg:msg?msg:[NSString stringWithFormat:@"%@%ld",NSLocalizedStringEx(@"UNKNOWN_ERROR", nil),(long)code]];
    }
    
        if (StrSame(identifier, @"SXUTORequestTypePeopleList")) {
    
            NSDictionary *data = responseObject[@"data"];
            NSDictionary *meta = data[@"meta"];
            NSString *current_page = meta[@"current_page"];// 当前页数
            NSString *last_page = meta[@"last_page"];// 最大页数
            
            NSArray *array = data[@"result"];
            
            if (pageNum == 1) {
            
                _dataArray = [UToPeopleManager mj_objectArrayWithKeyValuesArray:array];
            } else {

                [self.dataArray addObjectsFromArray:[UToPeopleManager mj_objectArrayWithKeyValuesArray:array]];
            }

            if ([current_page intValue]>=[last_page intValue]) {// current_page:当前页数;last_page:返回数据的最大页数(即总共有几页);>=即已经加载到最后一页数据了
                
                self.setTableView.mj_footer.state = MJRefreshStateNoMoreData;// 修改相应mj_footer.state的状态为MJRefreshStateNoMoreData
            } else {
                [self.setTableView.mj_footer resetNoMoreData];
            }
            
            if (_dataArray.count<=0) {
                
                [self.setTableView.mj_footer endRefreshingWithNoMoreData];
            } else {

            }
            [self.setTableView reloadData];
        }
}

// 网络请求失败
- (void)SXBaseNetWork:(SXBaseNetWork *)network faile:(NSError *)error identifier:(NSString *)identifier {
    
    [self.hud hideAnimated:NO];
    [self showHudNetworkError];
    if (self.setTableView.mj_header.isRefreshing) {
        
        [self.setTableView.mj_header endRefreshing];
    }
    if (self.setTableView.mj_footer.isRefreshing) {
        
        [self.setTableView.mj_footer endRefreshing];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    pageNum = 1;
    pageSize = 20;// 每页最多加载20条数据
    _dataArray = [NSMutableArray array];
    [self loadPeopleListData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UToColor backgroundGrayColor];
    [self.view addSubview:self.navView];
    [self.view addSubview:self.setTableView];
    [self.setTableView.mj_header beginRefreshing];// 一进入就开始下拉加载数据
}
#pragma mark -- 数据加载
// 加载员工列表
- (void)loadPeopleListData {
    
    pageNum = 1;
    NSDictionary *dic = @{@"token":[UToUser sharedUToUser].token,@"page":@(pageNum),@"per_page":@(pageSize)};
    SXUTONetWorkModel *model = [SXUTONetWorkModel UTONetWorkModelWithUTORequestType:SXUTORequestTypePeopleList parmeter:dic];
    if ([self.netWork request:model userToken:nil Identifier:@"SXUTORequestTypePeopleList"]) {
        
        self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.hud.delegate = self;
    }
}

// 加载更多员工列表
- (void)loadMorePeopleListData {
    
    pageNum ++;
    NSDictionary *dic = @{@"token":[UToUser sharedUToUser].token,@"page":@(pageNum),@"per_page":@(pageSize)};
    SXUTONetWorkModel *model = [SXUTONetWorkModel UTONetWorkModelWithUTORequestType:SXUTORequestTypePeopleList parmeter:dic];
    if ([self.netWork request:model userToken:nil Identifier:@"SXUTORequestTypePeopleList"]) {
        
        self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.hud.delegate = self;
    }
}
#pragma mark -- 懒加载
- (UToNavView *)navView {
    
    if (!_navView) {
        
        _navView = [[UToNavView alloc]init];
        [self.view addSubview:_navView];
        _navView.titleLabel.text = @"人员管理";
        [_navView.backBtn addTarget:self action:@selector(backClicked) forControlEvents:UIControlEventTouchUpInside];
        [_navView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.mas_equalTo(0);
            make.height.mas_equalTo(64);
            make.right.mas_equalTo(0);
            make.top.mas_equalTo(0);
        }];
    }
    return _navView;
}

- (void)backClicked {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (UToTableView *)setTableView {
    
    if (!_setTableView) {
        
        _setTableView = [[UToTableView alloc]init];
        [self.view addSubview:_setTableView];
        _setTableView.backgroundColor = [UToColor backgroundGrayColor];
        _setTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _setTableView.delegate = self;
        _setTableView.dataSource = self;
        _setTableView.scrollEnabled = YES;
        [_setTableView registerClass:[UToPeopleManagerCell class] forCellReuseIdentifier:@"UToPeopleManagerCellIdentifier"];
        [_setTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.right.mas_equalTo(0);
            make.top.mas_equalTo(self.navView.mas_bottom).offset(0);
            make.bottom.mas_equalTo(0);
        }];
        
        // 设置刷新控件
        header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadPeopleListData)];
        _setTableView.mj_header = header;
        footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMorePeopleListData)];
        _setTableView.mj_footer = footer;
        _setTableView.estimatedRowHeight = 0;// 解决上拉循环加载的问题(这里情况为后台返回数据非常多,很多页它会不停的加载,添加这句话即可解决)
        
        // 自定义刷新标题
        [header setTitle:@"下拉刷新" forState:MJRefreshStateIdle];
        [header setTitle:@"松开即可刷新" forState:MJRefreshStatePulling];
        [header setTitle:@"Loading ..." forState:MJRefreshStateRefreshing];
        [footer setTitle:@"上拉可以加载更多" forState:MJRefreshStateIdle];
        [footer setTitle:@"Loading more ..." forState:MJRefreshStateRefreshing];
        [footer setTitle:@"没有更多数据啦" forState:MJRefreshStateNoMoreData];
    }
    return _setTableView;
}

#pragma mark -- UITableviewDelegate && UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UToPeopleManagerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UToPeopleManagerCellIdentifier"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.peopleManagerModel = _dataArray[indexPath.row];
    cell.rightBtn.hidden = YES;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

@end

3.其他demo(BBX)

//
//  BBXShareProfitRecordViewController.m
//  DriverBBX
//
//  Created by Kevin on 2022/3/14.
//  Copyright © 2022 bbxpc.com. All rights reserved.
//

#import "BBXShareProfitRecordViewController.h"
#import "BBXPayRecordListCell.h"
#import 
#import "NetworkClient.h"
#import "BBXShareProfitDetailViewController.h"
#import "BBXShareProfitRecordModel.h"

@interface BBXShareProfitRecordViewController ()

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) int page;
@property (nonatomic, assign) int count;
@property (nonatomic, strong) BBXShareProfitRecordModel *shareProfitModel;

@end

@implementation BBXShareProfitRecordViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setNavGradientStyle];
    [self headerRefresh];//下拉刷新
    [self.navigationController.navigationBar setHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"分润信息";
    self.view.backgroundColor = [UIColor colorWithHexString:@"F1F2F4"];
    self.page = 1;
    [self.view addSubview:self.tableView];
}

核心下拉上拉处理逻辑代码:

#pragma mark -- 网络请求 && 上下拉刷新
- (void)headerRefresh {
    self.page = 1;
    self.count = 0;
    [self getShareProfitRecordIsClear:YES];
}

- (void)footerRefresh {
    self.page++;
    [self getShareProfitRecordIsClear:NO];
}

//中信分润策略查询接口
- (void)getShareProfitRecordIsClear:(BOOL)clear {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    
    NSString *url = @"/openCharge/getCiticShareInfoList";
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:@(self.page) forKey:@"page"];
    [paraDic setObject:[BBXDriverInfo shareManager].uid forKey:@"driver_id"];
    [paraDic setObject:@(10) forKey:@"rows"];
    __weak __typeof(self)weakSelf = self;
    [[NetworkClient sharedInstance] cj_agentPostDomainName:url domainParams:paraDic encrypt:YES completeBlock:^(NSDictionary *responseObject) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf.tableView.mj_footer resetNoMoreData];
        [strongSelf.tableView.mj_header endRefreshing];
        [strongSelf.tableView.mj_footer endRefreshing];
        if(![responseObject isKindOfClass:[NSDictionary class]]) {
            [strongSelf.view showRequestFailToast:nil];
            return;
        }
        NSString *status = responseObject[@"status"];
        NSString *message = responseObject[@"message"];
        if(status.integerValue != 0) {
            [strongSelf.view showRequestFailToast:message];
            return;
        }
        NSArray *arr = responseObject[@"data"];
        if(![arr isKindOfClass:[NSArray class]]) {
            [strongSelf.view showRequestFailToast:nil];
            return;
        }
        
        if (clear) {
            [strongSelf.dataArray removeAllObjects];
        }
        
        NSMutableArray *dataList = [[NSMutableArray alloc] initWithArray:arr];
        if (arr.count < 10) {
            [strongSelf.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
        int count = [responseObject[@"count"] intValue];
        if (strongSelf.count < count) {
            if (strongSelf.count == 0) {
                self.dataArray = [BBXShareProfitRecordModel mj_objectArrayWithKeyValuesArray:arr];
            } else {
                [self.dataArray addObjectsFromArray:[BBXShareProfitRecordModel mj_objectArrayWithKeyValuesArray:arr]];
            }
            strongSelf.count += (int)dataList.count;
        }
        [strongSelf.tableView reloadData];
    }];
}
#pragma mark -- UITableViewDelegate && UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 125;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BBXPayRecordListCell *cell = [[BBXPayRecordListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BBXPayRecordListCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (self.dataArray.count>0) {
        self.shareProfitModel = self.dataArray[indexPath.row];
        cell.payContentLB.text = self.shareProfitModel.share_name;
        cell.paystatusLB.text = self.shareProfitModel.share_stat_name;
        if (kStrEqual(cell.paystatusLB.text, @"已完成")) {
            cell.paystatusLB.textColor = BBXLightGray;
        } else {
            cell.paystatusLB.textColor = BBXRed;
        }
        [cell.moneyLB rz_colorfulConfer:^(RZColorfulConferrer * _Nonnull confer) {
            confer.text(@"¥ ").font(kFont(15));
            confer.text([NSString stringWithFormat:@"%.2f",[self.shareProfitModel.all_share_amt doubleValue]]).font(kFont_Bold(22));
            confer.text(@"累计到账").textColor(BBXGray).font(kFont(14));
        }];
        if (self.shareProfitModel.start_date.length>=8) {
            NSString *year = [self.shareProfitModel.start_date substringWithRange:NSMakeRange(0, 4)];
            NSString *month = [self.shareProfitModel.start_date substringWithRange:NSMakeRange(4, 2)];
            NSString *date = [self.shareProfitModel.start_date substringWithRange:NSMakeRange(6, 2)];
            cell.payTimeLB.text = [NSString stringWithFormat:@"开始日期:%@-%@-%@",year,month,date];
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BBXShareProfitDetailViewController *VC = [[BBXShareProfitDetailViewController alloc]init];
    BBXShareProfitRecordModel *model = self.dataArray[indexPath.row];
    VC.shareProfitModel = model;
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark -- 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = BBXBgGray;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
        [_tableView registerClass:[BBXPayRecordListCell class] forCellReuseIdentifier:@"BBXPayRecordListCell"];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.right.mas_equalTo(0);
            make.top.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
        }];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
        [footer setTitle:@"没有更多的数据了" forState:MJRefreshStateNoMoreData];
        _tableView.mj_footer = footer;
    }
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}

- (BBXShareProfitRecordModel *)shareProfitModel {
    if (!_shareProfitModel) {
        _shareProfitModel = [[BBXShareProfitRecordModel alloc]init];
    }
    return _shareProfitModel;
}

你可能感兴趣的:(iOS-MJ刷新小结(下拉+上拉))