概述:
Refresh control 是ios6之后新添加的刷新控件,它的使用非常简单,出现在表格的顶部,当表格出现下拉的时候,出现动画效果告诉用户,表格正在加载。像现在的微博,QQ,twitter的客户端,无处不见这种加载效果。
代码:
要使用Refresh control,我们要实现它的addTarget:action:forControlEvents: 实例方法,在今天这个demo里面,我们需要一个UItableView
@property (nonatomic, strong) NSMutableArray *times; @property (nonatomic, strong) UIRefreshControl *refreshControl;
初始化表格的时候,重载的方法:
- (id)initWithStyle:(UITableViewStyle)style{ self = [super initWithStyle:style]; if (self) { self.times = [NSMutableArray arrayWithObject:[NSDate date]]; /* Create the refresh control */ self.refreshControl = [[UIRefreshControl alloc] init]; self.refreshControl = self.refreshControl; [self.refreshControl addTarget:self action:@selector(handleRefresh:) forControlEvents:UIControlEventValueChanged]; } return self; }
添加表格数据和添加refresh control 的target:
- (void) handleRefresh:(id)paramSender{ /* Put a bit of delay between when the refresh control is released and when we actually do the refreshing to make the UI look a bit smoother than just doing the update without the animation */ int64_t delayInSeconds = 1.0f; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ /* Add the current date to the list of dates that we have so that when the table view is refreshed, a new item will appear on the screen so that the user will see the difference between the before and the after of the refresh */ [self.times addObject:[NSDate date]]; [self.refreshControl endRefreshing]; [self.tableView reloadData]; }); }
表格的数据源的方法:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return self.times.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } cell.textLabel.text = [NSString stringWithFormat:@"%@", self.times[indexPath.row]]; return cell; }
实现效果如下: