接上一個話題,實現了TabBar的點擊刷新之後,開始繼續寫完成功能,刷新UITableView,因而考慮到iOS 10
之後,UIScrollView
已經有UIRefreshControl
的屬性了,乾脆用自帶的寫。因而就有了以下的代碼:bash
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
refreshControl.tintColor = [UIColor grayColor];
refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"下拉刷新"];
[refreshControl addTarget:self action:@selector(refreshTabView) forControlEvents:UIControlEventValueChanged];
self.newsTableView.refreshControl = refreshControl;
複製代碼
-(void)refreshTabView
{
//添加一條數據
[self.newsData insertObject:[self.newsData firstObject] atIndex:0];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.newsTableView reloadData];
if ([self.newsTableView.refreshControl isRefreshing]) {
[self.newsTableView.refreshControl endRefreshing];
}
});
}
複製代碼
-(void)doubleClickTab:(NSNotification *)notification{
//這裏有個坑 就是直接用NSInteger接收會有問題 數字不對
//由於上個界面傳過來的時候封裝成了對象,因此用NSNumber接收後再取值
NSNumber *index = notification.object;
if ([index intValue] == 1) {
//刷新
[self.newsTableView.refreshControl beginRefreshing];
}
}
複製代碼
此時的效果以下,直接下拉刷新能夠,可是點擊TabBar不能夠:ui
通過Google幫助,終於知道緣由,由於系統自帶的UIRefreshControl有兩個陷阱:spa
-beginRefreshing
方法不會觸發UIControlEventValueChanged
事件;-beginRefreshing
方法不會自動顯示進度圈。也就是說,只是調用-beginRefreshing
方法是無論用的,那麼對應的須要作兩件事:3d
只須要修改上面第3步中的代碼以下:code
-(void)doubleClickTab:(NSNotification *)notification{
//這裏有個坑 就是直接用NSInteger接收會有問題 數字不對
//由於上個界面傳過來的時候封裝成了對象,因此用NSNumber接收後再取值
NSNumber *index = notification.object;
if ([index intValue] == 1) {
//刷新
//animated不要爲YES,不然菊花會卡死
[self.newsTableView setContentOffset:CGPointMake(0, self.newsTableView.contentOffset.y - self.newsTableView.refreshControl.frame.size.height) animated:NO];
[self.newsTableView.refreshControl beginRefreshing];
[self.newsTableView.refreshControl sendActionsForControlEvents:UIControlEventValueChanged];
}
}
複製代碼
最終效果: cdn