問(wèn)題描述
接上一個(gè)話(huà)題,實(shí)現(xiàn)了TabBar的點(diǎn)擊刷新以后,開(kāi)始繼續(xù)寫(xiě)完成功能,刷新UITableView僧叉,于是考慮到iOS 10
以后,UIScrollView
已經(jīng)有UIRefreshControl
的屬性了棺榔,干脆用自帶的寫(xiě)瓶堕。于是就有了如下的代碼:
- 添加UIRefreshControl到UITableView上去
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
{
//添加一條數(shù)據(jù)
[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];
}
});
}
- TabBar點(diǎn)擊事件
-(void)doubleClickTab:(NSNotification *)notification{
//這里有個(gè)坑 就是直接用NSInteger接收會(huì)有問(wèn)題 數(shù)字不對(duì)
//因?yàn)樯蟼€(gè)界面?zhèn)鬟^(guò)來(lái)的時(shí)候封裝成了對(duì)象,所以用NSNumber接收后再取值
NSNumber *index = notification.object;
if ([index intValue] == 1) {
//刷新
[self.newsTableView.refreshControl beginRefreshing];
}
}
此時(shí)的效果如下症歇,直接下拉刷新可以郎笆,但是點(diǎn)擊TabBar不可以:
刷新異常情況.gif
分析問(wèn)題
經(jīng)過(guò)Google幫助,終于知道原因忘晤,因?yàn)橄到y(tǒng)自帶的UIRefreshControl有兩個(gè)陷阱:
- 調(diào)用
-beginRefreshing
方法不會(huì)觸發(fā)UIControlEventValueChanged
事件宛蚓; - 調(diào)用
-beginRefreshing
方法不會(huì)自動(dòng)顯示進(jìn)度圈。
也就是說(shuō)设塔,只是調(diào)用-beginRefreshing
方法是不管用的凄吏,那么對(duì)應(yīng)的需要做兩件事:
- 手動(dòng)設(shè)置UIRefreshControl的事件;
- 手動(dòng)設(shè)置UITableView的ContentOffset闰蛔,露出進(jìn)度圈痕钢。
解決問(wèn)題
只需要修改上面第3步中的代碼如下:
-(void)doubleClickTab:(NSNotification *)notification{
//這里有個(gè)坑 就是直接用NSInteger接收會(huì)有問(wèn)題 數(shù)字不對(duì)
//因?yàn)樯蟼€(gè)界面?zhèn)鬟^(guò)來(lái)的時(shí)候封裝成了對(duì)象,所以用NSNumber接收后再取值
NSNumber *index = notification.object;
if ([index intValue] == 1) {
//刷新
//animated不要為YES序六,否則菊花會(huì)卡死
[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];
}
}
最終效果:
刷新正常情況.gif