在UIScrollView、UICollectionView和UITableView中添加UIRefreshControl实现下拉刷新

2,493 阅读2分钟

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

iOS 10 新特性

从iOS 10开始,UIScrollView增加了一个refreshControl属性,用于把配置好的UIRefreshControl赋值给该属性,这样UIScrollView就有了下拉刷新功能。和之前在UITableViewController中使用一样,不需要设置UIRefreshControlframe,只需要配置UIRefreshControl

因为UITableViewUICollectionView继承自UIScrollView,所以UITableViewUICollectionView也继承了refreshControl属性,也就是可以很方便的把刷新控件添加到滚动视图、集合视图和表视图(不再需要表视图控制器)。

截止目前,Xcode 8.2.1的Interface Builder还没有支持refreshControl属性,如果你需要在UIScrollViewUITableViewUICollectionView中使用UIRefreshControl只能通过代码添加。通过Interface Builder可以为UITableViewController 添加刷新控件。

滚动视图示例

这个demo使用Single View Application模板,打开storyboard,在系统创建的ViewController上添加一个UIScrollView,在UIScrollView上添加两个UILabel,并在UILabel上添加内容。想要实现的功能是,下拉刷新页面时隐藏第二个UILabel,再次刷新时显示该UILabel

这里只对demo简单描述,如果需要查看详细代码,可以在我的GitHub中查看。另外,文章底部也会提供源码地址。

创建刷新控件

UIScrollViewUITableViewUICollectionView中创建刷新控件步骤是一样的。在这个示例中,在ViewControllerviewDidLoad方法中创建并配置UIRefreshControlscrollView是连接到Interface Builder中的UIScrollView的IBOutlet属性。

- (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;
    }
}

注意以下几点:

  1. UIScrollView从iOS 10开始才有refreshControl属性,所以第一步判断当前系统版本。
  2. 初始化刷新控件。UIKit会自动设置frame,不需要手动设定。
  3. 3.1 配置刷新控件,可以通过tintColor设置进度滚轮指示器颜色,通过attributedTitle添加刷新时显示的提示文字。3.2 添加响应事件,当UIControlEventValueChanged事件发生时指定响应的动作。
  4. 把上面创建、配置的refreshControl赋值给scrollViewrefreshControl属性

现在实现动作方法。available是在interface部分声明的BOOL类型的对象。

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

如果secondLabel目前显示,下拉后隐藏,如果目前隐藏,下拉后显示。最后使用endRefreshing停止刷新。

Demo名称:RefreshControl
源码地址:github.com/pro648/Basi…

参考资料:

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

本文地址:github.com/pro648/tips…