我为我的作品设置了部分 横向 UICollectionView。我想让我的单元格项目在每一节的第二行的宽度是第一行项目的两倍。这是我设置的。
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return 2
}
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { //1.7, 2.7
if indexPath.row == 0 {
return CGSize(width: collectionView.frame.size.width/2,
height: collectionView.frame.size.height/2)
}
return CGSize(width: collectionView.frame.size.width,
height: collectionView.frame.size.height/2)
}
但这是最终的结果。
我怎样才能去除小尺寸项目中的空格,并使其布局美观?
注意:图片上的数字代表的是节和行的大小,但最终的结果是:我怎样才能把小尺寸的项目中的空格去掉,并把它们排好? 图片上的数字代表节和行(0 1 -> 节0,行1)
这就是我想实现的目标。
第一:如果你使用storyboard,确保你正确地将集合视图的约束条件添加到它的超级视图中。
第二:添加集合视图单元格的约束条件。
第三:在storyboard的大小检查器中,将集合视图的估计大小改为无。
第四:在viewcontroller中添加UICollectionViewDelegateFlowLayout。
第五:添加下面这些代码。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 0 {
return CGSize(width: (collectionView.frame.size.width - 10)/2,
height: (collectionView.frame.size.height - 10)/2) // your desired height
}
return CGSize(width: (collectionView.frame.size.width - 10),
height: (collectionView.frame.size.height - 10)/2)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
你可以使用这个funcs。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
希望对你有帮助...
将indexPath.row替换为indexPath.section。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { //1.7, 2.7
if indexPath.section == 0 {
return CGSize(width: collectionView.frame.size.width/2,
height: collectionView.frame.size.height/2)
}
return CGSize(width: collectionView.frame.size.width,
height: collectionView.frame.size.height/2)
}