iosswiftuicollectionviewuiscrollviewuserdefaults

scrollToItem isn't working in my CollectionView?


Why scrollToItem isn't working in my CollectionView? I want to work scrollToItem on EnabledID. So what's a problem and how fixed it?

Code:

var dataArray = NSMutableArray() // dataArray is has a data from Database
var EnabledID = Int()

EnabledID = UserDefaults.standard.integer(forKey: "EnabledID")
    
if EnabledID == 0 {
        
    EnabledID = 1
    UserDefaults.standard.set(1, forKey: "EnabledID")
        
} else {
    if EnabledID < dataArray.count {
        let index = NSIndexPath(item: EnabledID, section: 0)
        self.myCollectionView.scrollToItem(at: index as IndexPath, at: .centeredVertically, animated: true)
    }
}
    

Solution

  • Try this code...

    Objective-C

    [collectionView setDelegate:self];
    [collectionView reloadData];
    [collectionView layoutIfNeeded];
    [collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
    

    Swift - 4.x

    collectionView.delegate = self
    collectionView.reloadData()
    collectionView.layoutIfNeeded()
    collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .top, animated: true)
    

    When the scroll direction is horizontal you need to use left,right or centeredHorizontally.

    top is for the vertical direction.

    collectionView.scrollToItem(at: index, at: .top, animated: true)