http://code4app.com/ios/快速集成下拉上拉刷新/52326ce26803fabc46000000
- (void)viewDidLoad
{
[super viewDidLoad];
//获取数据
[self firstLoadRefresData];
//下拉刷新
self.refreshControl = [[UIRefreshControl alloc]init];
self.refreshControl.tintColor=[UIColor blueColor];
[self.refreshControl addTarget:self action:@selector(controlEventValueChanged:) forControlEvents:UIControlEventValueChanged];
// 集成上拉加载控件
[self setupRefresh];
}
/**
* 集成刷新控件
*/
- (void)setupRefresh
{
[self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
self.tableView.footerRefreshingText = @"MJ哥正在帮你加载中,不客气";
}
- (void)footerRereshing
{
// 1.添加假数据
if ([self.docs hasNextPage]) {
[self setData:[[self.docs page]intValue]+1];
}
// 2.2秒后刷新表格UI
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 刷新表格
[self.tableView reloadData];
// (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
[self.tableView footerEndRefreshing];
});
}
-(void)controlEventValueChanged:(id)sender{
if (self.refreshControl.refreshing) {
self.refreshControl.attributedTitle=[[NSAttributedString alloc]initWithString:@"刷新中"];
[self performSelector:@selector(refreshData) withObject:nil afterDelay:0.5];
}
}
-(void)refreshData{
//请求数据
[self firstLoadRefresData];
//刷新表格
[self.tableView reloadData];
//完成刷新
[self.refreshControl endRefreshing];
self.refreshControl.attributedTitle=[[NSAttributedString alloc]initWithString:@"下拉刷新"];
}
使用AFNetworking库,取得数据。
-(void)setData:(int) p {
NSString *string = [NSString stringWithFormat:@"%@p=%d&ps=10", BaseURLString,p];
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
self.docs=(NSMutableDictionary *)responseObject;
NSMutableArray *doclist=[[NSMutableArray alloc]initWithCapacity:10];
[doclist addObjectsFromArray:self.infos];
[doclist addObjectsFromArray:[self.docs info]];
self.infos=doclist;
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alertView show];
}];
[operation start];
}