iOS UITableView下拉刷新上拉加载更多EGOTableViewPullRefresh类库使用初级剑侠篇(欢迎提建议和分享遇到的问题)

本文主要是介绍iOS UITableView下拉刷新上拉加载更多EGOTableViewPullRefresh类库使用初级剑侠篇(欢迎提建议和分享遇到的问题),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!


这篇文章说下:MJRefresh和  EGOTableViewPullRefresh 的使用方法最下面有原理说明,若有不对或者建议请评论指出,先谢谢了:

首先是英文原文和类库下载地址:https://github.com/emreberge/EGOTableViewPullRefresh 

   

然后创建好自己使用的tableview控件接着:

  • 添加 QuartzCore.framework 到你的工程中。

  • 将 EGOTableViewPullRefresh 拖到你的工程目录下。
     
然后在需要使用的类里写上

 

下拉是一个刷新的工作,所以需要我们添加的代码无非就是数据刷新的代码。

(1)在.h文件中添加如下代码

[plain]  view plain copy
  1. @interface ...ViewController : UITableViewController<EGORefreshTableHeaderDelegate>  
  2. {  
  3.     EGORefreshTableHeaderView *refreshTableHeaderView;  
  4.     BOOL reloading;  
  5. }  
  6. - (void)reloadTableViewDataSource;  
  7. - (void)doneLoadingTableViewData;  

(2)在- (void)viewDidLoad函数中添加下面的代码。

[plain]  view plain copy
  1. if (refreshTableHeaderView == nil) {  
  2.           
  3. <span style="white-space:pre">  </span>EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tableView.bounds.size.height, self.view.frame.size.width, self.tableView.bounds.size.height)];  
  4.     view.delegate = self;  
  5.     [self.tableView addSubview:view];  
  6.     refreshTableHeaderView = view;  
  7.     [view release];   
  8. }     
  9. //最后一次更新的时间  
  10. [refreshTableHeaderView refreshLastUpdatedDate];  

(3)在对应的.m文件中添加如下方法

[plain]  view plain copy
  1. #pragma mark -  
  2. #pragma mark Data Source Loading / Reloading Methods  
  3. //更新列表数据  
  4. - (void)reloadTableViewDataSource{  
  5.     [NSThread detachNewThreadSelector:@selector(updateNewsByPullTable) toTarget:self withObject:nil]; //异步加载数据,不影tableView动作  
  6.     reloading = YES;      
  7. }  
  8. //调用JSON服务获取数据  
  9. - (void)updateNewsByPullTable  
  10. {  
  11.     NSString *str = @"http://....../getAllNews.aspx";  
  12.     NSURL *url = [NSURL URLWithString:str];  
  13.     ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];  
  14.     [request startSynchronous];  
  15.       
  16.     //接收返回数据  
  17.     NSString *response = [request responseString];  
  18.     NSLog(@"%@",response);  
  19.     self.data = [response JSONValue];  
  20.     [self.tableView reloadData];  
  21. }  
  22.   
  23. - (void)doneLoadingTableViewData{  
  24.       
  25.     //model should call this when its done loading  
  26.     reloading = NO;  
  27.     [refreshTableHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];  
  28.       
  29. }  
  30.   
  31. #pragma mark -  
  32. #pragma mark UIScrollViewDelegate Methods  
  33.   
  34. - (void)scrollViewDidScroll:(UIScrollView *)scrollView{   
  35.       
  36.     [refreshTableHeaderView egoRefreshScrollViewDidScroll:scrollView];  
  37.       
  38. }  
  39.   
  40. - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{  
  41.       
  42.     [refreshTableHeaderView egoRefreshScrollViewDidEndDragging:scrollView];  
  43.       
  44. }  
  45.   
  46.   
  47. #pragma mark -  
  48. #pragma mark EGORefreshTableHeaderDelegate Methods  
  49.   
  50. - (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{  
  51.       
  52.     [self reloadTableViewDataSource];  
  53.     [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:3.0];  
  54.       
  55. }  
  56.   
  57. - (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{  
  58.       
  59.     return reloading; // should return if data source model is reloading  
  60.       
  61. }  
  62.   
  63. - (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{  
  64.       
  65.     return [NSDate date]; // should return date data source was last changed  
  66.       
  67. }  


4、总结

    总的来说,实现这一功能并不复杂,关键在于-(void)reloadTableViewDataSource这一方法。这里我试了一下,读取数据的操作必须是异步的,要不然和tableView下拉再上弹这个动作会有很明显的延迟。再一次感受到了开源类库的强大,感谢这些大神们的无私贡献,让我们这些iOS开发初学者有机会能做出漂亮的应用。







也可以设置一个基类然后其他uitableview继承它:

.h


static NSString *CELL_ID = @"cell_id";


@class BaseTableView;

@protocol BaseTableViewDelegate <NSObject>


@optional

//下拉事件

- (void)pullDown:(BaseTableView *)tableView;

//上拉事件

- (void)pullUp:(BaseTableView *)tableView;

//选中单元格事件

- (void)didSelectRowAtIndexPath:(BaseTableView *)tabelView indexPath:(NSIndexPath *)indexPath;


@end


typedefvoid(^PullDonwFinish)(void);

typedefvoid(^PullUpFinish)(void);


@interface BaseTableView :UITableView<EGORefreshTableHeaderDelegate,UITableViewDataSource, UITableViewDelegate>

{

   EGORefreshTableHeaderView *_refreshHeaderView;

BOOL _reloading;

   UIButton *_moreButton;

}


@property(nonatomic,retain) NSMutableArray *data;


//是否显示下拉控件

@property(nonatomic,assign)BOOL refreshHeader;

//是否有更多(下一页)

@property(nonatomic,assign)BOOL isMore;


@property(nonatomic,copy)PullDonwFinish finishBlock;

@property(nonatomic,copy)PullUpFinish pullUpBlock;

//上拉代理对象

@property(nonatomic,assign)id<BaseTableViewDelegate> refreshDelegate;




//自动执行下拉动作

-(void)launchRefreshing;


- (void)reloadTableViewDataSource;

- (void)doneLoadingTableViewData;



@end


#import "BaseTableView.h
@implementation BaseTableView


- (id)initWithFrame:(CGRect)frame

{

   self = [superinitWithFrame:frame];

   if (self) {

        // Initialization code

        [self_initViews];

    }

    return self;

}


- (void)awakeFromNib {

    [superawakeFromNib];

    [self_initViews];

}


- (void)_initViews {

    

   self.backgroundColor =RGB(242, 243, 240);

    

    self.refreshHeader =YES;

   self.isMore =YES;

   self.delegate =self;

    self.dataSource =self;

    

    _moreButton = [UIButtonbuttonWithType:UIButtonTypeCustom];

   _moreButton.frame =CGRectMake(0,0, self.width,44);

    _moreButton.backgroundColor = [UIColorclearColor];

    [_moreButtonsetTitle:@""forState:UIControlStateNormal];

    _moreButton.titleLabel.font = [UIFontsystemFontOfSize:12.0f];

    [_moreButtonsetTitleColor:[UIColorlightGrayColor] forState:UIControlStateNormal];

    [_moreButtonaddTarget:selfaction:@selector(loadMoreAction)forControlEvents:UIControlEventTouchUpInside];

    

    UIActivityIndicatorView *activityView = [[UIActivityIndicatorViewalloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];

    activityView.frame =CGRectMake(90,10, 20, 20);

    [activityViewstopAnimating];

    activityView.tag =2013;

    [_moreButtonaddSubview:activityView];

    

    self.tableFooterView =_moreButton;

}


-(void)launchRefreshing

{

    if (_reloading) {

       _reloading = NO;

        

        [UIViewanimateWithDuration:0.4animations:^{

            [selfsetContentOffset:CGPointMake(0, -80)];

        }completion:^(BOOL finished) {

           if (finished) {

               //设置停止拖拽

                [_refreshHeaderViewperformSelector:@selector(egoRefreshScrollViewDidEndDragging:)withObject:selfafterDelay:0.2];

            }

        }];

    }else{

        //下拉之前还原_refreshHeaderViewstate

        [_refreshHeaderViewsetState:EGOOPullRefreshNormal];

        

        [UIViewanimateWithDuration:0.4animations:^{

            [selfsetContentOffset:CGPointMake(0, -80)];

        }completion:^(BOOL finished) {

           if (finished) {

                [_refreshHeaderViewsetState:EGOOPullRefreshPulling];

               //设置停止拖拽

                [_refreshHeaderViewperformSelector:@selector(egoRefreshScrollViewDidEndDragging:)withObject:selfafterDelay:0.2];

            }

        }];

    }

}


- (void)setRefreshHeader:(BOOL)refreshHeader {

   _refreshHeader = refreshHeader;

    

    if (self.refreshHeader) {

        if (_refreshHeaderView ==nil) {

           //创建下拉控件

            _refreshHeaderView = [[EGORefreshTableHeaderViewalloc] initWithFrame:CGRectMake(0.0f,0.0f - self.bounds.size.height,self.frame.size.width,self.bounds.size.height)];

            _refreshHeaderView.delegate =self;

            _refreshHeaderView.backgroundColor = [UIColorclearColor];

            [_refreshHeaderViewrefreshLastUpdatedDate];

        }

        

        [selfaddSubview:_refreshHeaderView];

    }else {

       if (_refreshHeaderView.superview !=nil) {

            [_refreshHeaderViewremoveFromSuperview];

        }

    }

}


//上拉按钮的点击事件

- (void)loadMoreAction {

    

   if (self.pullUpBlock !=nil) {

       self.pullUpBlock();

    }

    

    //调用代理对象的协议方法

   if ([self.refreshDelegaterespondsToSelector:@selector(pullUp:)]) {

        [self.refreshDelegatepullUp:self];

    }

    

    [_moreButtonsetTitle:@"正在加载..."forState:UIControlStateNormal];

    UIActivityIndicatorView *activityView = (UIActivityIndicatorView *)[_moreButtonviewWithTag:2013];

    [activityViewstartAnimating];

}


- (void)setIsMore:(BOOL)isMore {

   _isMore = isMore;

   if (self.isMore) {

        [_moreButtonsetTitle:@"加载更多数据"forState:UIControlStateNormal];

       _moreButton.enabled =YES;

    }else {

        [_moreButtonsetTitle:@"没有更多数据"forState:UIControlStateNormal];

       _moreButton.enabled =NO;

    }

    

    UIActivityIndicatorView *activityView = (UIActivityIndicatorView *)[_moreButtonviewWithTag:2013];

    [activityViewstopAnimating];

}


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

{

    [tableView deselectRowAtIndexPath:indexPathanimated:YES];

}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return self.data.count;

}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    UITableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:CELL_ID];

   if (!cell) {

        cell = [[UITableViewCellalloc] initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:CELL_ID];

    }

   return cell;

}


/*________________________下拉控件相关方法________________________________*/

#pragma mark -

#pragma mark Data Source Loading / Reloading Methods


- (void)reloadTableViewDataSource{

    _reloading = YES;

    

}


//收起下拉刷新

- (void)doneLoadingTableViewData{

    _reloading = NO;

    [_refreshHeaderViewegoRefreshScrollViewDataSourceDidFinishedLoading:self];

}



#pragma mark -

#pragma mark UIScrollViewDelegate Methods


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

    

    [_refreshHeaderViewegoRefreshScrollViewDidScroll:scrollView];

    

}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{

    

    [_refreshHeaderViewegoRefreshScrollViewDidEndDragging:scrollView];

    

    //偏移量.y + tableView.height =内容的高度

    //h是上拉超出来的尺寸

   float h = scrollView.contentOffset.y + scrollView.height - scrollView.contentSize.height;

   if (h > 30 &&self.isMore) {

        [selfloadMoreAction];

    }

}



#pragma mark -

#pragma mark EGORefreshTableHeaderDelegate Methods

//下拉到一定距离,手指放开时调用

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{

    

    [selfreloadTableViewDataSource];

    

    //停止加载,弹回下拉

    // [self performSelector:@selector(doneLoadingTableViewData)

    //               withObject:nil afterDelay:3.0];

   if (self.finishBlock !=nil) {

       self.finishBlock();

    }

    

   if ([self.refreshDelegaterespondsToSelector:@selector(pullDown:)]) {

        [self.refreshDelegatepullDown:self];

    }

}


- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{

    

    return_reloading;// should return if data source model is reloading

}


//取得下拉刷新的时间

- (NSDate *)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{

    

    return [NSDatedate]; // should return date data source was last changed

    

}



@end

 浅谈下拉刷新和上拉加载更多原理:

下文出自:  http://blog.csdn.net/hmt20130412/article/details/32695305

 很多App中,新闻或者展示类都存在下拉刷新和上拉加载的效果,网上提供了实现这种效果的第三方类(详情请见MJRefresh和  EGOTableViewPullRefresh ),用起来很方便,但是闲暇之余,我们可以思考下,这种效果实现的原理是什么,我以前说过,只要是动画都是骗人的,只要不是硬件问题大部分效果都能在系统UI的基础上做出来. 

            @下面是关键代码分析:

// 下拉刷新的原理
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{if (scrollView.contentOffset.y < - 100) {
  
  [UIView animateWithDuration:1.0 animations:^{
      
      //  frame发生偏移,距离顶部150的距离(可自行设定)
      self.tableView.contentInset = UIEdgeInsetsMake(150.0f, 0.0f, 0.0f, 0.0f);
  } completion:^(BOOL finished) {
      
      /**
       *  发起网络请求,请求刷新数据
       */  }];}
}// 上拉加载的原理
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{NSLog(@"%f",scrollView.contentOffset.y);NSLog(@"%f",scrollView.frame.size.height);NSLog(@"%f",scrollView.contentSize.height);/***  关键-->*  scrollView一开始并不存在偏移量,但是会设定contentSize的大小,所以contentSize.height永远都会比contentOffset.y高一个手机屏幕的*  高度;上拉加载的效果就是每次滑动到底部时,再往上拉的时候请求更多,那个时候产生的偏移量,就能让contentOffset.y + 手机屏幕尺寸高大于这*  个滚动视图的contentSize.height*/if (scrollView.contentOffset.y + scrollView.frame.size.height >= scrollView.contentSize.height) {
  
  NSLog(@"%d %s",__LINE__,__FUNCTION__);
  [UIView commitAnimations];
  
  [UIView animateWithDuration:1.0 animations:^{
      //  frame发生的偏移量,距离底部往上提高60(可自行设定)
      self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 60, 0);
  } completion:^(BOOL finished) {
      
      /**
       *  发起网络请求,请求加载更多数据
       *  然后在数据请求回来的时候,将contentInset改为(0,0,0,0)
       */
  }];}
}

这篇关于iOS UITableView下拉刷新上拉加载更多EGOTableViewPullRefresh类库使用初级剑侠篇(欢迎提建议和分享遇到的问题)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1088524

相关文章

python使用库爬取m3u8文件的示例

《python使用库爬取m3u8文件的示例》本文主要介绍了python使用库爬取m3u8文件的示例,可以使用requests、m3u8、ffmpeg等库,实现获取、解析、下载视频片段并合并等步骤,具有... 目录一、准备工作二、获取m3u8文件内容三、解析m3u8文件四、下载视频片段五、合并视频片段六、错误

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

nginx启动命令和默认配置文件的使用

《nginx启动命令和默认配置文件的使用》:本文主要介绍nginx启动命令和默认配置文件的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录常见命令nginx.conf配置文件location匹配规则图片服务器总结常见命令# 默认配置文件启动./nginx

在Windows上使用qemu安装ubuntu24.04服务器的详细指南

《在Windows上使用qemu安装ubuntu24.04服务器的详细指南》本文介绍了在Windows上使用QEMU安装Ubuntu24.04的全流程:安装QEMU、准备ISO镜像、创建虚拟磁盘、配置... 目录1. 安装QEMU环境2. 准备Ubuntu 24.04镜像3. 启动QEMU安装Ubuntu4

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(