1.使用UIRefreshControl实现下拉刷新
//声明下拉刷新 self.refreshControl = [[UIRefreshControl alloc] init]; //赋予动作执行 [self.refreshControl addTarget:self action:@selector(refreshedByPullingTable:) forControlEvents:UIControlEventValueChanged];
//使用UIRefreshControl实现下拉刷新 - (void) refreshedByPullingTable:(id)sender { //开始执行 [self.refreshControl beginRefreshing]; //模拟延迟, double delayInSeconds = 2.0; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ //下拉刷新结束 [self.refreshControl endRefreshing]; }); }
2.无限滚动
首先需要引用:EgoRefreshTableHeaderView,PullToRefreshViewController
.h 文件:注意继承父类
#import <UIKit/UIKit.h> #import "PullToRefreshViewController.h" //必须继承 @interface ViewController : PullToRefreshViewController @end
#import "ViewController.h" @interface ViewController () @property (assign,nonatomic) int pageCount; @end @implementation ViewController @synthesize pageCount = _pageCount; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //现在拥有几个片段 self.numberOfSections = 1; //标示现在是第几页 self.pageCount = 1; //标题 self.title = NSLocalizedString(@"Infinite Scrolling", @""); //设置导航-标题栏是否透明 self.navigationController.navigationBar.translucent = NO; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } //下拉刷新的方法 - (void) doRefresh { //仅仅是模拟延时,使用时需要替换为需要的方法 double delayInSeconds = 2.0; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds*NSEC_PER_SEC); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ self.loading = NO; }); } //无限滚动的方法 - (void)loadMore { //模拟延时 double delayInSeconds = 2.0; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ //刷新后,当前页+1 self.pageCount++; //如果当前到第五页了,则停止无限滚动 if(self.pageCount==5) self.endReached = YES; //重新加载数据。 [self.tableView reloadData]; }); } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if(section == self.numberOfSections) { //直接调用父类 PullToRefreshViewController中 的方法。 //片段加一(可以看下 PullToRefreshViewController.m 中方法的详细) return [super tableView:tableView numberOfRowsInSection:section]; } //根据有多少页,返回相应的记录数 return 20*self.pageCount; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { if(indexPath.section==self.numberOfSections) { //直接调用父类 PullToRefreshViewController中 的方法。 //设置最后一行为:加载更多 return [super tableView:tableView cellForRowAtIndexPath:indexPath]; } static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(!cell) { cell = [[UITableViewCell alloc] init]; } cell.textLabel.text = [NSString stringWithFormat:@"Row %d",indexPath.row]; return cell; } @end