Collection View layout bug when selectItem (Swift 5)

杀马特。学长 韩版系。学妹 提交于 2021-02-17 01:52:51

问题


After selecting cell from viewDidLoad Layout is change

Before select cell

Before select cell

After select cell

let indexPath = IndexPath(row: SelectedFolderIndex, section: 0)       
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredVertically)

After select cell

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!