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...

相关文章
相关标签/搜索