Reputation: 881
I currently have a collection view that does horizontal paging where each cell is fullscreen. What I want to do is for the collectionview to start at a specific index when it shows.
Right now I'm using scrollToItemAtIndexPath:atScrollPosition:animated: with animated set to NO but that still loads the first index first before it can scroll to the specific item. It also seems I can only use this method in ViewDidAppear so it shows the first cell and then blinks to the cell that I want to show. I hide this by hiding the collection view until the scroll has finished but it doesn't seem ideal.
Is there any better way to do this other than the way I described it?
Upvotes: 54
Views: 37416
Reputation: 146
Just found me in the same problem, and make it work by adding this piece of code in willDisplayCell
delegate call
private var firstLoad: Bool = true
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if self.firstLoad {
let initialIndexPath = <initial index path>
collectionView.scrollToItem(
at: initialIndexPath,
at: <UICollectionView.ScrollPosition>,
animated: false
)
self.firstLoad = false
}
}
Upvotes: 0
Reputation: 295
A simpler solution inspired by others:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
DispatchQueue.main.async {
self.collectionView.scrollToItem(at: lastIndexPath, section: 0), at: .centeredHorizontally, animated: false)
}
}
It will work if you put the code inside DispatchQueue.main.async block.
Upvotes: 7
Reputation: 5103
Unfortunately, every single one of these existing answers is at least partly wrong or does not answer the exact question being asked. I worked through this issue with a co-worker who was not helped by any of these responses.
All you need to do is set the content offset without animation to the correct content offset and then call reload data. (Or skip the reloadData call if it has not been loaded at all yet.) You should do this in viewDidLoad if you never want the first cell to be created.
This answer assumes the collection view scrolls horizontally and the size of the cells are the same size as the view but the concept is the same if you want to scroll vertically or the cells are a different size. Also if your CollectionView has more than one section you have to do a bit more math to calculate the content offset but the concept is still the same.
func viewDidLoad() {
super.viewDidLoad()
let pageSize = self.view.bounds.size
let contentOffset = CGPoint(x: pageSize.width * self.items.count, y: 0)
self.collectionView.setContentOffset(contentOffset, animated: false)
}
Upvotes: 11
Reputation: 5188
So I solved this a different way, using the UICollectionViewDelegate
method and a one-off Bool
:
Swift 2:
var onceOnly = false
internal func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if !onceOnly {
let indexToScrollTo = NSIndexPath(forRow: row, inSection: section)
self.problemListCollectionView.scrollToItemAtIndexPath(indexToScrollTo, atScrollPosition: .Left, animated: false)
onceOnly = true
}
}
Swift 3:
var onceOnly = false
internal func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if !onceOnly {
let indexToScrollTo = IndexPath(item: row, section: section)
self.problemListCollectionView.scrollToItem(at: indexToScrollTo, at: .left, animated: false)
onceOnly = true
}
}
This code is executed before any animation occurs (so it really loads to this point), which is better than attempting to call in viewDidAppear
, and I didn't have success with it in viewWillAppear
.
Upvotes: 67
Reputation: 1359
I came here having this same issue and found that in my case, this issue was caused my the ViewController in my storyboard being set as 'freeform' size.
I guess viewWillLayoutSubviews gets called to calculate the correct size when the view is first loaded if the storyboard's dimensions leave this unclear. (I had sized my viewController in my storyboard as to be 'freeform' so I could make it very tall to see/edit many cells in long tableView inside my collectionView).
I found that victor.vasilica's & greenhouse's approach re: putting the 'scrollToRow' command in viewWillLayoutSubviews did work perfectly to fix the issue.
However, I also found that once I made the VC in my storyboard 'fixed' size again, the issue immediately went away and I was able to set the initial cell from viewWillAppear. Your situation may be different, but this helped me understand what was going on in my situation and I hope my answer might help inform others with this issue.
Upvotes: 0
Reputation: 1511
To solve this problem I partially used the greenhouse answer.
/// Edit
var startIndex: Int! = 0
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
collectionView.setNeedsLayout()
collectionView.layoutIfNeeded()
collectionView.scrollToItemAtIndexPath(
NSIndexPath(forItem: 0, inSection: startIndex),
atScrollPosition: .None,
animated: false)
}
The problem seems to be in the wrong collectionView
size. After setting the layout scrollToItemAtIndexPath
produces the needed result.
It also seems that this problem only persists when a Collection View
is used inside a UIViewController
.
Upvotes: 21
Reputation: 711
Hey I have Solved With Objective c . I think this is useful for you. You can convert Objective c to swift as well . Here is my Code:
**In My case , On button click I activate the specific index , that is 3 **
for Vertical
- (IBAction)Click:(id *)sender {
NSInteger index=3;
CGFloat pageHeight = self.collectionView.frame.size.height;
CGPoint scrollTo = CGPointMake(0, pageHeight * index);
[self.collectionView setContentOffset:scrollTo animated:YES];
}
For Horizontal
- (IBAction)Click:(id *)sender {
NSInteger index=3;
CGFloat pageWidth = self.collectionView.frame.size.width;
CGPoint scrollTo = CGPointMake(pageWidth * index, 0);
[self.collectionView setContentOffset:scrollTo animated:YES];
}
I hope it may help You.
Upvotes: -1
Reputation: 17616
Swift 3.0 tested and works.
var onceOnly = false
internal func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if !onceOnly {
//set the row and section you need.
let indexToScrollTo = IndexPath(row: 1, section: indexPath.section)
self.fotmCollectionView.scrollToItem(at: indexToScrollTo, at: .left, animated: false)
onceOnly = true
}
}
Upvotes: 6
Reputation: 1316
Here is what worked for me (in a UICollectionViewController class):
private var didLayoutFlag: Bool = false
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let collectionView = self.collectionView {
if !self.didLayoutFlag {
collectionView.scrollToItemAtIndexPath(self.viewModel.initialIndexPath, atScrollPosition: .None, animated: false)
self.didLayoutFlag = true
}
}
}
Upvotes: 3
Reputation: 1281
this seemed to work for me:
- (void)viewDidLayoutSubviews
{
[self.collectionView layoutIfNeeded];
NSArray *visibleItems = [self.collectionView indexPathsForVisibleItems];
NSIndexPath *currentItem = [visibleItems objectAtIndex:0];
NSIndexPath *nextItem = [NSIndexPath indexPathForItem:someInt inSection:currentItem.section];
[self.collectionView scrollToItemAtIndexPath:nextItem atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
}
Upvotes: 2
Reputation: 2842
Pass the indexPath from the first VC to the collection view in the DidSelectItemAtIndexPath method. In viewDidLoad of your collection view, use the method scrollToItemAtIndexPath:atScrollPosition:animated:
Set animated
to NO
and atScrollPosition
to UICollectionViewScrollPositionNone
. Like this:
[self.collectionView scrollToItemAtIndexPath:self.indexPathFromVC atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
Upvotes: 2