新浪微博的app中有一个功能,就是点击一个tabBarItem时,表格会自动下拉刷新,不需要人手工操作。
以前写过新浪微博app的Demo,但当时一直没想明白以上功能是怎么做到的,现在找到方法了,很简单,就是在点击按钮后,设置Table View的contentOffset就可以了。
首先是UIRefreshControl的初始化代码:
- (void)viewDidLoad { [super viewDidLoad]; self.marray = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3", nil]; // 初始化UITableViewController的UIRefreshControl组件 self.refreshControl = [[UIRefreshControl alloc] init]; self.refreshControl.tintColor = [UIColor blueColor]; [self.refreshControl addTarget:self action:@selector(controlEventValueChanged:) forControlEvents:UIControlEventValueChanged]; } #pragma mark - Refresh control - (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 { // 生成随机数,并加入marray数组中 unsigned int randomNumber = arc4random() % 10; NSString *randomData = [NSString stringWithFormat:@"%i", randomNumber]; [self.marray addObject:randomData]; // 刷新表格 [self.tableView reloadData]; // 完成刷新 [self.refreshControl endRefreshing]; self.refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"下拉刷新"]; }
现在在导航栏中加一个按钮,并编写其响应方法:
#pragma mark - Navigation item action - (IBAction)refreshTable:(id)sender { // 自行创建下拉动画 [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:1.0]; self.tableView.contentOffset = CGPointMake(0.0, -200.0); // 注意位移点的y值为负值 [UIView commitAnimations]; // 改变refreshControl的状态 [self.refreshControl beginRefreshing]; self.refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"刷新中"]; // 刷新数据和表格视图 [self performSelector:@selector(refreshData) withObject:nil afterDelay:2.0]; }
运行起来看看:
完成。还是自己跑下Demo比较好:点此进入下载页
原文:http://blog.csdn.net/u010962810/article/details/19305369