IOS怎么实现一个UITableView的下拉刷新
採用的EGORefreshTableHeaderView来实现:
在Controller上实现EGORefreshTableHeaderDelegate的delegate
@property(nonatomic)UITableView* tableView; @property(nonatomic)NSMutableArray* data; @property(nonatomic)EGORefreshTableHeaderView* refreshTableVIew; @property(nonatomic,assign)BOOL reloading;先初始化:
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. UIToolbar* bar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(click)]; [bar setItems:[NSArray arrayWithObjects:item, nil]]; [self.view addSubview:bar]; self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44,320,460-44)]; [self.view addSubview:_tableView]; self.tableView.delegate = self; self.tableView.dataSource = self; _data = [[NSMutableArray alloc] init]; [_data addObject:@"aa"]; [_data addObject:@"cc"]; if (_refreshTableVIew == nil) { EGORefreshTableHeaderView* refreshTableView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0, -self.tableView.bounds.size.height, self.view.frame.size.width, self.tableView.bounds.size.height)]; refreshTableView.delegate = self; [_tableView addSubview:refreshTableView]; _refreshTableVIew = refreshTableView; } }
下拉的时候会运行
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{ _reloading = YES; //開始刷新后运行后台线程,在此之前能够开启HUD或其它对UI进行堵塞 [NSThread detachNewThreadSelector:@selector(doInBackground) toTarget:self withObject:nil]; }
-(void)doInBackground{ NSLog(@"do in background"); [_data addObject:@"ff"]; [NSThread sleepForTimeInterval:3]; [self performSelectorOnMainThread:@selector(loadedTableViewData) withObject:nil waitUntilDone:YES]; }
-(void)loadedTableViewData{ _reloading = NO; [_refreshTableVIew egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView]; [self.tableView reloadData]; }
这种方法表示正在刷新中
- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{ return _reloading; }
这种方法在显示时间在TableView的刷新块上 :
//返回刷新时间的回调方法 -(NSDate *)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view { return [NSDate date]; }
然后必须加上以下两个方法:
-(void)scrollViewDidScroll:(UIScrollView *)scrollView { [_refreshTableVIew egoRefreshScrollViewDidScroll:scrollView]; } -(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate { [_refreshTableVIew egoRefreshScrollViewDidEndDragging:scrollView]; }