Apple在iOS 6中添加了UIRefreshControl
,但只能在UITableViewController
中使用,不能在UIScrollView
和UICollectionView
中使用。ios
從iOS 10開始,UIScrollView
增長了一個refreshControl
屬性,用於把配置好的UIRefreshControl
賦值給該屬性,這樣UIScrollView
就有了下拉刷新功能。和以前在UITableViewController
中使用同樣,不須要設置UIRefreshControl
的frame
,只須要配置UIRefreshControl
。git
由於UITableView
和UICollectionView
繼承自UIScrollView
,因此UITableView
和UICollectionView
也繼承了refreshControl
屬性,也就是能夠很方便的把刷新控件添加到滾動視圖、集合視圖和表視圖(再也不須要表視圖控制器)。github
截止目前,Xcode 8.2.1的 Interface Builder尚未支持refreshControl
屬性,若是你須要在UIScrollView
、UITableView
和UICollectionView
中使用UIRefreshControl
只能經過代碼添加。經過 Interface Builder能夠爲UITableViewController
添加刷新控件。
這個demo使用Single View Application模板,打開storyboard,在系統建立的ViewController
上添加一個UIScrollView
,在UIScrollView
上添加兩個UILabel
,並在UILabel
上添加內容。想要實現的功能是,下拉刷新頁面時隱藏第二個UILabel
,再次刷新時顯示該UILabel
。app
這裏只對demo簡單描述,若是須要查看詳細代碼,能夠在 個人GitHub中查看。另外,文章底部也會提供源碼地址。
在UIScrollView
、UITableView
和UICollectionView
中建立刷新控件步驟是同樣的。在這個示例中,在ViewController
的viewDidLoad
方法中建立並配置UIRefreshControl
。scrollView
是鏈接到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
UIScrollView
從iOS 10開始纔有refreshControl
屬性,因此第一步判斷當前系統版本。UIKit
會自動設置frame
,不須要手動設定。tintColor
設置進度滾輪指示器顏色,經過attributedTitle
添加刷新時顯示的提示文字。3.2 添加響應事件,當UIControlEventValueChanged
事件發生時指定響應的動做。refreshControl
賦值給scrollView
的refreshControl
屬性如今實現動做方法。available
是在interface部分聲明的BOOL
類型的對象。url
- (void)refresh:(UIRefreshControl *)sender { self.available = ! self.available; self.secondLabel.hidden = self.available; // 中止刷新 [sender endRefreshing]; }
若是secondLabel
目前顯示,下拉後隱藏,若是目前隱藏,下拉後顯示。最後使用endRefreshing
中止刷新。spa
Demo名稱:RefreshControl
源碼地址:https://github.com/pro648/Bas...code
參考資料:對象