How To Create Infinite Scrolling in my UICollectionView
?
attached screenshot :
Now my NSArray
is
NSArray* nameArr = [NSArray arrayWithObjects: @"0", @"1", @"2", @"3", @"4", nil];
I want to create an Infinite Scrolling in collectionView After Complete array repeat all cells again and again.
Left and Right both side required to scroll Infinite.
If yes, then how can I implement please give a reference in objective-c.
Thanks!!! In advance
First thing replace your current NSArray with NSMutableArray and make this changes as above in your cellForItemAtIndexPath
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return nameArr.count;
}
- (__kindof UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
UILabel *label = [cell viewWithTag:25];
[label setText:[NSString stringWithFormat:@"%ld",(long)indexPath.row]];
if(indexPath.row == nameArr.count-1) {
[nameArr addObjectsFromArray:nameArr.mutableCopy];
[collectionView reloadData];
}
return cell;
}
Here we are adding the same array objects again and again so it will be scroll infinite time.
Attached screenshot: Refer This
Hope this will help you
Had the same problem and i solved it by returning the number of items
in numberOfItemsInSection: by 2
-(NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section{
return _array.count * 2;
}
in cellForItemAtIndexPath i return the cell the usual way and if the index is higher than the _array.count the just subtract the _array.count from the index.
-(UICollectionViewCell *)collectionView:(UICollectionView
*)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
NSInteger index = indexPath.item;
if(index > _array.count - 1){
index -= _array.count;
}
CellView *cell = [collectionView
dequeueReusableCellWithReuseIdentifier:@"cellIdentifier"
forIndexPath:indexPath];
//To get the string from the array use
NSString string = [_array objectAtIndex:(index % _array.count)];
return cell;
}
Now the thing about this method is that i use only 2N items in the collectionView instead of a huge random number.
The trick is "put the 2 arrays side by side" and to keep the user in the middle using the offset.
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
int scrollViewWidth = scrollView.contentSize.width;
CGPoint offset = scrollView.contentOffset;
if(offset.x < scrollViewWidth /4){
offset.x += scrollViewWidth / 2;
[scrollView setContentOffset:offset];
} else if(offset.x > scrollViewWidth /4 *3){
offset.x -= scrollViewWidth / 2;
[scrollView setContentOffset:offset];
}
}