您的位置:首页 > 产品设计 > UI/UE

UITableView 滑动自动加载更多数据

2015-11-08 20:00 393 查看
//
//  ViewController.m
//  loadMoreTableDemo
//
//  Created by zhangcheng on 15/11/7.
//  Copyright © 2013年 zhangcheng. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,weak)UITableView *tabelView;
@property(nonatomic,strong)NSMutableArray *arrM;
@end

@implementation ViewController

- (NSMutableArray *)arrM{
if (_arrM == nil) {
_arrM = [NSMutableArray arrayWithObjects:@"A",@"A",@"A",@"A",@"A",@"A",@"A",@"A",@"A",@"A",@"A",@"A",@"A",@"A",@"A",@"A",@"A",@"A",nil];
}
return _arrM;
}

- (void)viewDidLoad {
[super viewDidLoad];

UITableView *tableView =[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
tableView.dataSource = self;
tableView.delegate = self;
[self.view addSubview:tableView];
self.tabelView = tableView;
}

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

NSInteger count = self.arrM.count;

return  count+1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *ID =@"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

cell =  [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];

NSInteger row = indexPath.row ;
if ( row == self.arrM.count ) {
cell.textLabel.text =@"查看更多";
}else{
cell.textLabel.text = [self.arrM objectAtIndex:indexPath.row];

}
return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row == self.arrM.count) {
[self performSelectorInBackground:@selector(loadMore) withObject:nil];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
return;
}
}

- (void)loadMore{
NSMutableArray *more;
more =  [NSMutableArray arrayWithObjects:@"最新数据", nil];
[self performSelectorOnMainThread:@selector(appendTableWith:) withObject:more waitUntilDone:NO];
}

- (void)appendTableWith:(NSMutableArray *)data{
for (int i=0; i<[data count]; i++) {
[self.arrM addObject:[data objectAtIndex:i]];
}

NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:[data count]];
for (int ind = 0; ind < [data count]; ind++) {
NSIndexPath *newPath =  [NSIndexPath indexPathForRow:[self.arrM indexOfObject:[data objectAtIndex:ind]] inSection:0];

[insertIndexPaths addObject:newPath];
}

[self.tabelView insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: