而在平时的开发中一般会用第三方的下拉刷新非常方便而且优化程度较高,在这里我简单介绍以下UIRefreshControl的用法,还是建议大家在开发中使用知名第三方的下拉刷新, 或者你也可以自己封装。使用方法如下:
1.目前只对UITableviewController有用;
2.只能下拉刷新,不能上拉刷新;
3.init或者viewdidload中创建UIRefreshControl,设置文字,颜色等信息;
4.系统自动管理UIRefreshControl,自动添加到tableview视图中;
5.给 UIRefreshControl添加方法,当值改变的时候调用,方法用于数据请求;6.该方法中请求数据确认完成之后,调用endRefreshing方法,关闭刷新;
#import "ViewController.h" #define KIPHONE_WIDTH [UIScreen mainScreen].bounds.size.width #define KIPHONE_HEIGHT [UIScreen mainScreen].bounds.size.height @interface ViewController ()<UITableViewDataSource,UITableViewDelegate> @property (nonatomic, strong) UITableView *mainTableView; @property (nonatomic) NSInteger rowCount; @property (nonatomic, strong) UIRefreshControl *refreshControl; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self configureTableView]; UIRefreshControl *refresh = [[UIRefreshControl alloc] init]; refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"下拉刷新"]; refresh.tintColor = [UIColor blueColor]; //下拉刷新的事件,通过UIControlEventValueChanged触发 [refresh addTarget:self action:@selector(pullToRefresh) forControlEvents:UIControlEventValueChanged]; self.refreshControl = refresh; [_mainTableView addSubview:_refreshControl]; } - (void)configureTableView { self.mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 50, KIPHONE_WIDTH, KIPHONE_HEIGHT) style:UITableViewStylePlain]; _mainTableView.delegate = self; _mainTableView.dataSource = self; _mainTableView.rowHeight = 44; _rowCount = 5; [self.view addSubview:_mainTableView]; } - (void)pullToRefresh { //设置刷新中的字符 self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"刷新中"]; //2秒延迟 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ //每次刷新增加5行 _rowCount += 5; [self.mainTableView reloadData]; //刷新结束时刷新控件的设置 [self.refreshControl endRefreshing]; //重新设置字符 self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"下拉刷新"]; }); } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return _rowCount; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; } cell.textLabel.text = @"我是打酱油的"; return cell; } @end