Ask Your Question
4

How can I make a UICollectionViewCell move to the next row if it goes beyond the width of the UICollectionView?

asked 2023-02-06 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-01-24 12:00:00 +0000

lalupa gravatar image

You can achieve this by implementing the UICollectionViewDelegateFlowLayout protocol and implementing the collectionView(_:layout:sizeForItemAt:) and collectionView(_:layout:insetForSectionAtIndex:) methods. Here's how you can do this in Swift:

  1. Conform to UICollectionViewDelegateFlowLayout protocol in your view controller:
class ViewController: UIViewController, UICollectionViewDelegateFlowLayout {
    // rest of your code
}
  1. Implement collectionView(_:layout:sizeForItemAt:) method to return the size of each cell:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // calculate the size of your cell based on your requirements
    return CGSize(width: 100, height: 100)
}
  1. Implement collectionView(_:layout:insetForSectionAtIndex:) method to return the section insets. This will be used later to calculate the available width for each row:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
}
  1. Finally, implement collectionView(_:didEndDisplaying:forItemAt:) method to calculate when a cell goes beyond the available width and needs to be moved to the next row:
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    let lastRow = collectionView.numberOfItems(inSection: 0) / 3 // assuming 3 columns in each row
    let currentRow = indexPath.item / 3

    // check if the cell is beyond the available width, and move it to the next row
    if currentRow > lastRow {
        collectionView.performBatchUpdates({
            let indexPath = IndexPath(item: collectionView.numberOfItems(inSection: 0), section: 0)
            collectionView.insertItems(at: [indexPath])
        }, completion: nil)
    }
}

Note that this implementation assumes a fixed width for each cell, and 3 columns in each row. You may need to modify the calculations as per your requirements.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-02-06 11:00:00 +0000

Seen: 18 times

Last updated: Jan 24 '22