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
参考资料:对象