#import "RootViewController.h"
@interface RootViewController ()
{
NSMutableArray *_dataArray;
UITableView *_tableView;
//iOS6之后 系统提供的实现下拉刷新的控件,配合UITableView使用
UIRefreshControl *_refreshControl;
}
@end
@implementation RootViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_dataArray = [[NSMutableArray alloc] init];
//得到假数据
for (int i=0; i<5; i++) {
NSString *str = [NSString stringWithFormat:@"测试%d",i];
[_dataArray addObject:str];
}
self.automaticallyAdjustsScrollViewInsets = NO;
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,64,320,416) style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
[self.view addSubview:_tableView];
//创建刷新控件,初始化后,此控件会自动有一个大小,将它添加到tableView之后,tableView会自动对它进行布局
_refreshControl = [[UIRefreshControl alloc] init];
//设置标题
_refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"下拉刷新"];
//拖拽tableView 会引起refreshControl坐标的变化,对应的事件UIControlEventValueChanged;action 中对应刷新方法
[_refreshControl addTarget:self action:@selector(refreshData) forControlEvents:UIControlEventValueChanged];
[_tableView addSubview:_refreshControl];
}
- (void)refreshData{
[_refreshControl beginRefreshing];//开始刷新
_refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"刷新中"];
//self 1.0秒之后,执行 addData方法。该方法表示执行完刷新的数据的之后再进行addData方法。即添加数据。该方法相当于应该定时器
[self performSelector:@selector(addData) withObject:nil afterDelay:1.0];
}
- (void)addData{
//每次下拉刷新都会添加新的数据。因为问往数据源中添加类对象。
[_dataArray addObject:@"add"];
//结束刷新
[_refreshControl endRefreshing];
//改标题。结束刷新的时候往要使标题回到最初的状态。
_refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"下拉刷新"];
//刷新数据。如果不刷新数据将没有新数据.一直使原来的数据。
[_tableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIde = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIde];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIde];
}
//把取出来的数据赋给cell的主标题。
cell.textLabel.text = [_dataArray objectAtIndex:indexPath.row];
return cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end