Search code examples
swiftxcodeuicollectionviewuicollectionviewcell

horizontal UIcollectionView Scroll start from right to left


I do want the view when it loads to show the right cell first then I should scroll left from there I try this code but didn't work

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! customCell
        cell.data = self.data[indexPath.row]
        self.collectionView.scrollToItem(at: IndexPath(item: self.data.count, section: 0) as IndexPath, at: .right, animated: false)
        return cell
    }

like this photo here when the view loads it shows the first right cell

enter image description here


Solution

  • Since UICollectionView scrolls horizontally from right to left equally, you can set your collection view when it appears, to appear scrolled to the maximum right ! so that the user can start scrolling from right to left

    YourCollectionView is the name of your desired CollectionView

    YourObjectListData is the Datasource for that collection view

    self.YourCollectionView.reloadData()
    self.YourCollectionView.scrollToItem(at: NSIndexPath(item: self.YourObjectListData.count - 1, section: 0) as IndexPath, at: .right, animated: false)