I\'m trying to add a UIRefreshControl
to a UICollectionView
, but the problem is that the refresh control does not appear unless the collection view
I'm calling beginRefreshing()
right after viewDidLoad()
, but on some screens it doesn't work. And only collectionView.layoutIfNeeded()
in viewDidLoad()
helped me
You must check in api call if collection view is in refreshing state then end refreshing to dismiss refreshing control.
private let refreshControl = UIRefreshControl()
refreshControl.tintColor = .white
refreshControl.addTarget(self, action: #selector(refreshData), for: .valueChanged)
collectionView.addSubview(refreshControl)
@objc func refreshData() {
// API Call
}
// Disable refresh control if already refreshing
if refreshControl.isRefreshing {
refreshControl.endRefreshing()
}
If your collectionview
has a content size big enough to scroll vertically, it's OK, but in your case it's not.
You must enable the property AlwaysBounceVertical
, so you could set self.collectionView.alwaysBounceVertical = YES;
Try this:
self.collectionView.alwaysBounceVertical = YES;
Complete code for a UIRefreshControl
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
refreshControl.tintColor = [UIColor grayColor];
[refreshControl addTarget:self action:@selector(refershControlAction) forControlEvents:UIControlEventValueChanged];
[self.collectionView addSubview:refreshControl];
self.collectionView.alwaysBounceVertical = YES;
Larry's answer in swift:
let refreshControl = UIRefreshControl()
refreshControl.tintColor = UIColor.blueColor()
refreshControl.addTarget(self, action: "refresh", forControlEvents: .ValueChanged)
collectionView.addSubview(refreshControl)
collectionView.alwaysBounceVertical = true
Swift 3:
let refreshControl = UIRefreshControl()
refreshControl.tintColor = .blue
refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
collectionView.addSubview(refreshControl)
collectionView.alwaysBounceVertical = true
Attributes/Scroll View/Bounce Vertically in Storyboard/Xib