在我的应用程序中,我将刷新控件与集合视图一起使用。
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds];
collectionView.alwaysBounceVertical = YES;
...
[self.view addSubview:collectionView];
UIRefreshControl *refreshControl = [UIRefreshControl new];
[collectionView addSubview:refreshControl];
iOS7有一些令人讨厌的错误,当您向下拉集合视图并且在刷新开始时不松开手指时,垂直contentOffset
向下移动20-30点,从而导致丑陋的滚动跳跃。
如果将它们与 UITableViewController
之外的刷新控件一起使用,表也会出现此问题。但是对于他们来说,通过将UIRefreshControl
实例分配给UITableView
的私有属性_refreshControl
可以轻松解决:
@interface UITableView ()
- (void)_setRefreshControl:(UIRefreshControl *)refreshControl;
@end
...
UITableView *tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds];
[self.view addSubview:tableView];
UIRefreshControl *refreshControl = [UIRefreshControl new];
[tableView addSubview:refreshControl];
[tableView _setRefreshControl:refreshControl];
但是UICollectionView
没有这样的属性,所以必须有某种方法来手动处理它。
遇到同样的问题,并找到了似乎可以解决它的解决方法。
这似乎是因为当您拉过滚动视图的边缘时,UIScrollView
会减慢平移手势的跟踪速度。但是,UIScrollView
不考虑跟踪期间对 contentInset 的更改。 UIRefreshControl
激活时会更改内容插入,此更改会导致跳转。
覆盖UICollectionView
setContentInset
并解释这种情况似乎有所帮助:
- (void)setContentInset:(UIEdgeInsets)contentInset {
if (self.tracking) {
CGFloat diff = contentInset.top - self.contentInset.top;
CGPoint translation = [self.panGestureRecognizer translationInView:self];
translation.y -= diff * 3.0 / 2.0;
[self.panGestureRecognizer setTranslation:translation inView:self];
}
[super setContentInset:contentInset];
}
有趣的是,UITableView
通过拉过刷新控件之前不会减慢跟踪速度来解释这一点。但是,我没有看到这种行为暴露的方式。
- (void)viewDidLoad
{
[super viewDidLoad];
self.refreshControl = [[UIRefreshControl alloc] init];
[self.refreshControl addTarget:self action:@selector(scrollRefresh:) forControlEvents:UIControlEventValueChanged];
[self.collection insertSubview:self.refreshControl atIndex:0];
self.refreshControl.layer.zPosition = -1;
self.collection.alwaysBounceVertical = YES;
}
- (void)scrollRefresh:(UIRefreshControl *)refreshControl
{
self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"Refresh now"];
// ... update datasource
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"Updated %@", [NSDate date]]];
[self.refreshControl endRefreshing];
[self.collection reloadData];
});
}