TableView下拉刷新

效果图

下拉刷新tableview的数据,每次刷新添加一个“新添加的元素”,代码如下:

ViewController.m

#import "ViewController.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>{
    UITableView *table;
    NSMutableArray *arr;//数据源
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"title";
    // 创建表格
    table = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    table.dataSource = self;
    table.delegate = self;
    table.rowHeight = 50;
    [self.view addSubview:table];
    //创建数据
    arr=[NSMutableArray arrayWithObjects:@"张三",@"李四",@"王五", nil];
    //创建下拉属性
    table.refreshControl=[[UIRefreshControl alloc]init];
    //编辑下拉属性
    table.refreshControl.tintColor=[UIColor lightGrayColor];
    table.refreshControl.backgroundColor = [UIColor orangeColor];
    table.refreshControl.attributedTitle=[[NSAttributedString alloc]initWithString:@"下拉刷新"];
    [table.refreshControl addTarget:self action:@selector(xl) forControlEvents:UIControlEventValueChanged];
}
//下拉等待2秒
-(void)xl{
    table.refreshControl.attributedTitle=[[NSAttributedString alloc]initWithString:@"正在刷新..."];
    [self performSelector:@selector(sx) withObject:nil afterDelay:2];
}
//刷新
-(void)sx{
    NSMutableArray *ay=[NSMutableArray arrayWithObjects:@"新添加的元素", nil];
    [arr addObjectsFromArray:ay];
    table.refreshControl.attributedTitle=[[NSAttributedString alloc]initWithString:@"刷新完成"];
    [table.refreshControl endRefreshing];
    [table reloadData];
    table.refreshControl.attributedTitle=[[NSAttributedString alloc]initWithString:@"下拉刷新"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ident = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ident];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ident];
    }
    cell.textLabel.text = arr[indexPath.row];
    
    return cell;
}

推荐阅读更多精彩内容