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

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

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

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

创建刷新控件

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

 1 - (void)viewDidLoad
 2 {
 3     [super viewDidLoad];
 4     
 5     // 1 先判断系统版本
 6     if ([NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10,0,0}])
 7     {
 8         // 2 初始化
 9         UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
10         
11         // 3.1 配置刷新控件
12         refreshControl.tintColor = [UIColor brownColor];
13         NSDictionary *attributes = @{NSForegroundColorAttributeName : [UIColor redColor]};
14         refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull To Refresh" attributes:attributes];
15         // 3.2 添加响应事件
16         [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
17         
18         // 4 把创建的refreshControl赋值给scrollView的refreshControl属性
19         self.scrollView.refreshControl = refreshControl;
20     }
21 }

注意以下几点:

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

现在实现动作方法。

1 - (void)refresh:(UIRefreshControl *)sender
2 {
3    //做相关刷新处理
4     
5     // 停止刷新
6     [sender endRefreshing];
7 }

 

 

转自:https://github.com/pro648/tips/wiki/%E5%9C%A8UIScrollView%E3%80%81UICollectionView%E5%92%8CUITableView%E4%B8%AD%E6%B7%BB%E5%8A%A0UIRefreshControl%E5%AE%9E%E7%8E%B0%E4%B8%8B%E6%8B%89%E5%88%B7%E6%96%B0

posted @ 2019-10-15 17:44  洛洛沙  阅读(434)  评论(0)    收藏  举报