苹果在IOS 6 API中加入了下拉刷新控件;并且IOS 6之后,UITableViewController中增加了一个refreshControl属性,这个属性保持了UIRefreshControl的一个对象指针。UIRefreshControl是IOS 6为表视图实现下拉刷新而提供的类,目前该类只应用于表视图界面。UIRefreshControl的refreshControl属性与UITableViewController配合使用,关于下拉刷新布局等问题可以不必考虑,UITableViewController会将其自动放入表视图中。
下面是一个简单的下拉刷新实现:
// ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UITableViewController
@property (strong,nonatomic) NSMutableArray *data;
@end
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
{
NSDateFormatter *dateFormater;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
dateFormater=[[NSDateFormatter alloc] init];
[dateFormater setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
self.data=[NSMutableArray arrayWithObject:[[NSDate alloc] init]];
//UIRefreshControl
UIRefreshControl *refreshCtrl=[[UIRefreshControl alloc] init];
//The styled title text to display in the refresh control.
refreshCtrl.attributedTitle=[[NSAttributedString alloc] initWithString:@"下拉刷新"];
//A touch dragging or otherwise manipulating a control, causing it to emit a series of different values.
[refreshCtrl addTarget:self action:@selector(refresh) forControlEvents:UIControlEventValueChanged];
self.refreshControl=refreshCtrl;
}
-(void) refresh
{
//A Boolean value indicating whether a refresh operation has been triggered and is in progress. (read-only)
if(self.refreshControl.refreshing){
self.refreshControl.attributedTitle=[[NSAttributedString alloc] initWithString:@"正在加载..."];
NSDate *date=[[NSDate alloc] init];
[self performSelector:@selector(finishLoad:) withObject:date afterDelay:5];
}
}
-(void) finishLoad:(id) obj
{
[self.refreshControl endRefreshing];
self.refreshControl.attributedTitle=[[NSAttributedString alloc] initWithString:@"下拉刷新"];
[self.data addObject:obj];
[self.tableView reloadData];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.data count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier=@"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(!cell){
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.textLabel.text=[dateFormater stringFromDate:[self.data objectAtIndex:indexPath.row]];
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
-(void)didReceiveMemoryWarning
{
dateFormater=nil;
self.refreshControl=nil;
[self.data removeAllObjects];
self.data=nil;
}
@end