Apple在iOS 6中添加了UIRefreshControl
,但只能在UITableViewController
中使用,不能在UIScrollView
和UICollectionView
中使用。
iOS 10 新特性
從iOS 10開始,UIScrollView
增加了一個(gè)refreshControl
屬性,用于把配置好的UIRefreshControl
賦值給該屬性,這樣UIScrollView
就有了下拉刷新功能。和之前在UITableViewController
中使用一樣,不需要設(shè)置UIRefreshControl
的frame
,只需要配置UIRefreshControl
。
因?yàn)?code>UITableView和UICollectionView
繼承自UIScrollView
,所以UITableView
和UICollectionView
也繼承了refreshControl
屬性,也就是可以很方便的把刷新控件添加到滾動(dòng)視圖、集合視圖和表視圖(不再需要表視圖控制器)。
截止目前,Xcode 8.2.1的Interface Builder還沒有支持
refreshControl
屬性,如果你需要在UIScrollView
、UITableView
和UICollectionView
中使用UIRefreshControl
只能通過代碼添加。通過Interface Builder可以為UITableViewController
添加刷新控件。
滾動(dòng)視圖示例
這個(gè)demo使用Single View Application模板,打開storyboard,在系統(tǒng)創(chuàng)建的ViewController
上添加一個(gè)UIScrollView
,在UIScrollView
上添加兩個(gè)UILabel
,并在UILabel
上添加內(nèi)容。想要實(shí)現(xiàn)的功能是,下拉刷新頁面時(shí)隱藏第二個(gè)UILabel
,再次刷新時(shí)顯示該UILabel
。
這里只對(duì)demo簡單描述,如果需要查看詳細(xì)代碼,可以在我的GitHub中查看。另外,文章底部也會(huì)提供源碼地址。
創(chuàng)建刷新控件
在UIScrollView
、UITableView
和UICollectionView
中創(chuàng)建刷新控件步驟是一樣的。在這個(gè)示例中,在ViewController
的viewDidLoad
方法中創(chuàng)建并配置UIRefreshControl
。scrollView
是連接到Interface Builder中的UIScrollView
的IBOutlet屬性。
- (void)viewDidLoad
{
[super viewDidLoad];
// 1 先判斷系統(tǒng)版本
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 添加響應(yīng)事件
[refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
// 4 把創(chuàng)建的refreshControl賦值給scrollView的refreshControl屬性
self.scrollView.refreshControl = refreshControl;
}
}
注意以下幾點(diǎn):
-
UIScrollView
從iOS 10開始才有refreshControl
屬性,所以第一步判斷當(dāng)前系統(tǒng)版本。 - 初始化刷新控件。
UIKit
會(huì)自動(dòng)設(shè)置frame
,不需要手動(dòng)設(shè)定。 - 3.1 配置刷新控件,可以通過
tintColor
設(shè)置進(jìn)度滾輪指示器顏色,通過attributedTitle
添加刷新時(shí)顯示的提示文字。3.2 添加響應(yīng)事件,當(dāng)UIControlEventValueChanged
事件發(fā)生時(shí)指定響應(yīng)的動(dòng)作。 - 把上面創(chuàng)建、配置的
refreshControl
賦值給scrollView
的refreshControl
屬性
現(xiàn)在實(shí)現(xiàn)動(dòng)作方法。available
是在interface部分聲明的BOOL
類型的對(duì)象。
- (void)refresh:(UIRefreshControl *)sender
{
self.available = ! self.available;
self.secondLabel.hidden = self.available;
// 停止刷新
[sender endRefreshing];
}
如果secondLabel
目前顯示,下拉后隱藏,如果目前隱藏,下拉后顯示。最后使用endRefreshing
停止刷新。
Demo名稱:RefreshControl
源碼地址:https://github.com/pro648/BasicDemos-iOS
參考資料: