我们都知道在iOS10前 UIRefreshControl 只对UITableviewController使用,其他类使用会崩溃,但是在iOS10 UIRefreshControl 将支持所有的 UIScrollView 以及其子类,比如说 UICollectionView,UITableView等。
代码示例:
1. 我们先新建一个UIScrollerView:
@property (strong, nonatomic) UIScrollView *scrollerView;
self.scrollerView = [[UIScrollView alloc] initWithFrame:self.view.frame];
self.scrollerView.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
[self.view addSubview:self.scrollerView];
2. 在scrollerView上面放一个view:
UIView *testView = [[UIView alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width, self.view.frame.size.height)];
testView.backgroundColor = [UIColor greenColor];
[self.scrollerView addSubview:testView];
3. 初始化UIRefreshControl的一个对象,并设置颜色,标题和下拉时触发的刷新方法:
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
refreshControl.tintColor = [UIColor grayColor];
refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"下拉刷新"];
[refreshControl addTarget:self action:@selector(refreshAction) forControlEvents:UIControlEventValueChanged];
4. 把生成的refreshControl赋值给scrollerView的refreshControl:
self.scrollerView.refreshControl = refreshControl;
下拉刷新方法:
-(void)refreshAction
{
NSLog(@"下拉刷新");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.scrollerView.refreshControl endRefreshing]; //结束刷新
});
}
由于太简单了,这里就不写Demo了。