iOS開發之UIRefreshControl使用踩坑

問題描述

接上一個話題,實現了TabBar的點擊刷新以后,開始繼續寫完成功能,刷新UITableView,于是考慮到iOS 10以后,UIScrollView已經有UIRefreshControl的屬性了,干脆用自帶的寫。于是就有了如下的代碼:

  1. 添加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;

  1. 下拉刷新事件
-(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];
        }
    });
}
  1. TabBar點擊事件
-(void)doubleClickTab:(NSNotification *)notification{
    
    //這里有個坑 就是直接用NSInteger接收會有問題 數字不對
    //因為上個界面傳過來的時候封裝成了對象,所以用NSNumber接收后再取值
    NSNumber *index = notification.object;
    
    if ([index intValue] == 1) {
        //刷新
        [self.newsTableView.refreshControl beginRefreshing];
        
    }
    
}

此時的效果如下,直接下拉刷新可以,但是點擊TabBar不可以:

刷新異常情況.gif

分析問題

經過Google幫助,終于知道原因,因為系統自帶的UIRefreshControl有兩個陷阱:

  1. 調用-beginRefreshing方法不會觸發UIControlEventValueChanged事件;
  2. 調用-beginRefreshing方法不會自動顯示進度圈。

也就是說,只是調用-beginRefreshing方法是不管用的,那么對應的需要做兩件事:

  1. 手動設置UIRefreshControl的事件;
  2. 手動設置UITableView的ContentOffset,露出進度圈。

解決問題

只需要修改上面第3步中的代碼如下:

-(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];
    }
    
}

最終效果:


刷新正常情況.gif
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容