selectItem (Swift 5) 时的集合视图布局错误
Collection View layout bug when selectItem (Swift 5)
select从 viewDidLoad 布局更改单元格后
在 select 单元格之前
select单元格后
let indexPath = IndexPath(row: SelectedFolderIndex, section: 0)
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredVertically)
布局
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
当您设置 scrollPosition: .centeredVertically
时,您设置的是在滚动后所有项目将位于中心并垂直对齐,就像您在您的案例中看到的那样。尝试查看 https://developer.apple.com/documentation/uikit/uicollectionview/1618057-selectitem 以更改您想要的行为
您需要从单元格宽度中删除插图和间距:
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)
}
select从 viewDidLoad 布局更改单元格后
在 select 单元格之前
select单元格后
let indexPath = IndexPath(row: SelectedFolderIndex, section: 0)
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredVertically)
布局
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
当您设置 scrollPosition: .centeredVertically
时,您设置的是在滚动后所有项目将位于中心并垂直对齐,就像您在您的案例中看到的那样。尝试查看 https://developer.apple.com/documentation/uikit/uicollectionview/1618057-selectitem 以更改您想要的行为
您需要从单元格宽度中删除插图和间距:
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)
}