问题
After selecting cell from viewDidLoad Layout is change
Before select cell
After select cell
let indexPath = IndexPath(row: SelectedFolderIndex, section: 0)
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredVertically)
Layout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width/2.2, height: 55)
}
ViewDidLoad
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 7, left: 12, bottom: 12, right: 12)
layout.minimumInteritemSpacing = 5
layout.minimumLineSpacing = 11
collectionView!.collectionViewLayout = layout
collectionView.delegate = self
collectionView.dataSource = self
collectionView.allowsMultipleSelection = false
回答1:
You need to cut insets and spacing from cell width:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (collectionView.frame.width/2.2) - 2*12 - 11
return CGSize(width: width, height: 55)
}
回答2:
When you set scrollPosition: .centeredVertically
you are setting that after the scroll al the items will be positioned in the center and aligned vertically, like you can see in your case. Try look at https://developer.apple.com/documentation/uikit/uicollectionview/1618057-selectitem for change the behavior you want
来源:https://stackoverflow.com/questions/59910957/collection-view-layout-bug-when-selectitem-swift-5