ScrollView、CollectionView和TableView添加UIRefreshControl實現下拉刷新

Apple在iOS 6中添加了UIRefreshControl,但只能在UITableViewController中使用,不能在UIScrollViewUICollectionView中使用。ios

iOS 10 新特性

從iOS 10開始,UIScrollView增長了一個refreshControl屬性,用於把配置好的UIRefreshControl賦值給該屬性,這樣UIScrollView就有了下拉刷新功能。和以前在UITableViewController中使用同樣,不須要設置UIRefreshControlframe,只須要配置UIRefreshControlgit

由於UITableViewUICollectionView繼承自UIScrollView,因此UITableViewUICollectionView也繼承了refreshControl屬性,也就是能夠很方便的把刷新控件添加到滾動視圖、集合視圖和表視圖(再也不須要表視圖控制器)。github

截止目前,Xcode 8.2.1的 Interface Builder尚未支持 refreshControl屬性,若是你須要在 UIScrollViewUITableViewUICollectionView中使用 UIRefreshControl只能經過代碼添加。經過 Interface Builder能夠爲 UITableViewController 添加刷新控件。

滾動視圖示例

這個demo使用Single View Application模板,打開storyboard,在系統建立的ViewController上添加一個UIScrollView,在UIScrollView上添加兩個UILabel,並在UILabel上添加內容。想要實現的功能是,下拉刷新頁面時隱藏第二個UILabel,再次刷新時顯示該UILabelapp

RefreshControlStoryboard.png

這裏只對demo簡單描述,若是須要查看詳細代碼,能夠在 個人GitHub中查看。另外,文章底部也會提供源碼地址。

建立刷新控件

UIScrollViewUITableViewUICollectionView中建立刷新控件步驟是同樣的。在這個示例中,在ViewControllerviewDidLoad方法中建立並配置UIRefreshControlscrollView是鏈接到Interface Builder中的UIScrollView的IBOutlet屬性。ide

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 1 先判斷系統版本
    if ([NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10,0,0}])
    {
        // 2 初始化
        UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
        
        // 3.1 配置刷新控件
        refreshControl.tintColor = [UIColor brownColor];
        NSDictionary *attributes = @{NSForegroundColorAttributeName : [UIColor redColor]};
        refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull To Refresh" attributes:attributes];
        // 3.2 添加響應事件
        [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
        
        // 4 把建立的refreshControl賦值給scrollView的refreshControl屬性
        self.scrollView.refreshControl = refreshControl;
    }
}

注意如下幾點:ui

  1. UIScrollView從iOS 10開始纔有refreshControl屬性,因此第一步判斷當前系統版本。
  2. 初始化刷新控件。UIKit會自動設置frame,不須要手動設定。
  3. 3.1 配置刷新控件,能夠經過tintColor設置進度滾輪指示器顏色,經過attributedTitle添加刷新時顯示的提示文字。3.2 添加響應事件,當UIControlEventValueChanged事件發生時指定響應的動做。
  4. 把上面建立、配置的refreshControl賦值給scrollViewrefreshControl屬性

如今實現動做方法。available是在interface部分聲明的BOOL類型的對象。url

- (void)refresh:(UIRefreshControl *)sender
{
    self.available = ! self.available;
    self.secondLabel.hidden = self.available;
    
    // 中止刷新
    [sender endRefreshing];
}

若是secondLabel目前顯示,下拉後隱藏,若是目前隱藏,下拉後顯示。最後使用endRefreshing中止刷新。spa

RefreshControl.gif

Demo名稱:RefreshControl
源碼地址:https://github.com/pro648/Bas...code

參考資料:對象

  1. Refresh Control Changes in iOS 10
  2. What's New in UICollectionView in iOS 10

本文地址:https://github.com/pro648/tip...

相關文章
相關標籤/搜索